phpsymfonysymfony-security

Why does the "@IsGranted" annotation does not work if I also configure security using "security.yaml"?


I have a controller, where I use the @IsGranted(IS_AUTHENTICATED_ANONYMOUSLY) annotation to allow all users to access, and I also have a security.yaml.

But I the annotation does not seem to work.

Controller

    /**
     * @Route("/example",name="app_example")
     * @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
     */
    public function example(): RedirectResponse
    {
        /// omit
    }

security.yaml

  access_control:
    - { path: ^/, roles: ROLE_ADMIN }

When I access /example, I'm requested to login.

I know I can manage by moving IS_AUTHENTICATED_ANONYMOUSLY to security.yaml but I want to know the way to use annotation.


Solution

  • The @IsGranted() (from SensioFrameworkExtraBundle) is checked on an event that comes after Symfony Security access control.

    Since you have contradictory configurations (your main security configuration demands authentication on all routes, and your the annotation on your controller simply says "no authentication on this route"), the main security configuration "wins".

    If you want to have security configuration both in the configuration file and as annotations, the configuration shouldn't overlap and contradict each other.

    If they conflict, for the @IsGranted() annotations to work they can be more restrictive than the main security configuration, but not more open.