Best practice to allow access to owner user and ad

2020-02-16 03:59发布

问题:

I'm programming a site in Symfony2, using FOSUserBundle for managing user access. I have an entity called "Site" which can have many Users. Only the related users and the admins should have access to the Site:show action.

I don't know if it's possible to do this in security.yml or if I have to do it directly in the controller or somewhere else. What's the recommended way?

Thanks.

回答1:

If you want to restrict access per user at the object level, then you're looking for ACLs. ProblematicAclManagerBundle is a nice wrapper to simplify ACL usage in controllers.

Otherwise, if you want to limit access per role, then you can use routes and roles defined in security.yml

Here's a sample of what it should look like:

access_control:
  - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  - { path: ^/admin, role: ROLE_ADMIN }
  - { path: ^/.*, role: [IS_AUTHENTICATED_ANONYMOUSLY] }

In your controller, you can also use:

use JMS\SecurityExtraBundle\Annotation\Secure;

/**
 * @Route("/home", name="home") 
 * @Secure(roles="ROLE_USER")
 */
public function indexAction()
{
    ...
}