FOSRestBundle / JMSSerializerBundle: Interacting with Symfony2 Security Roles

I want to serialize and return only a few attributes of my object using JMSSerializerBundle and FOSRestBundle.

For example, I have the following attributes:

User

  • Username
  • Email
  • Birthday
  • Comments

Comments

  • Text
  • DateTime

Users with role ROLE_ADMIN should get the serialized object of the entire user object. ROLE_USER should only receive username and all comments.

What's the easiest way to implement a Symfony2 security component in a JMSSerializerBundle? Or do I need to implement this in my controller and serialize it "manually"?

Many thanks

+3


source to share


1 answer


I don't think you need to do it all manually. It looks like serialization groups might be a good solution.

use JMS\Serializer\Annotation\Groups;

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

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

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

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

      

In your controller, you just need to check the role and use 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 allows you to role-protect methods on the controller. Provide a different route / method for each parameter and give folder access control.

+3


source







All Articles