Ueli
Ueli

Reputation: 2411

FOSRestBundle / JMSSerializerBundle: interact with Symfony2 Security roles

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

For example I have this attributes:

User

Comments

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

Upvotes: 3

Views: 2560

Answers (1)

Quint
Quint

Reputation: 776

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.

Upvotes: 3

Related Questions