Domanda

I want to serialize and return only a few attributes of my entity with JMSSerializerBundle and FOSRestBundle.

For example I have this attributes:

User

  • Username
  • E-Mail
  • Birthday
  • Comments

Comments

  • Text
  • DateTime

Users with the role ROLE_ADMIN should get a serialized object of the whole user-object. ROLE_USER should only get the username and all comments.

What's the easiest way to implement the Symfony2 Security Component in JMSSerializerBundle? Or do I need to implement this in my controller and serialize it "by hand"?

Thank you very much

È stato utile?

Soluzione

I don't think you have to do it all by hand. It sounds like serialization groups might be a good solution here.

use JMS\Serializer\Annotation\Groups;

/** @Groups({"admin", "user"}) */
$username

/** @Groups({"admin"}) */
$email

/** @Groups({"admin"}) */
$birthday

/** @Groups({"admin", "user"}) */
$comments

In your controller, it would just be a matter of checking the role and using the correct serialization group.

$serializer = $this->container->get('serializer');
$serializer->setGroups(array("admin")); or $serializer->setGroups(array("admin","user"));

Another option would be the JMSSecurityExtraBundle which lets you secure methods on your controller by role. Provide a different route/method for each option and let the bundle handle access control.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top