How do I check for user role in symfony2 for urls not falling under patterns defined security.yml?

Enable the firewall on the whole app using the ^/ pattern, permit anonymous access and use access_control to restrict access:

security:
    firewalls:
        secured_area:
            pattern: ^/
            anonymous: ~

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

As @itsmequinn suggested, use the isGranted() method of the security context:

if ($this->get('security.context')->isGranted('ROLE_BRAND')) {
    // the user has the ROLE_BRAND role, so act accordingly
}

In Symfony 2.6, security.context has been split into two separate services. Hence you need to use the security.authorization_checker service to solve the problem:

if ($this->get('security.authorization_checker')->isGranted('ROLE_BRAND')) {
    // the user has the ROLE_BRAND role, so act accordingly
}

SecurityContext will be deprecated in Symfony 3.0

Prior to Symfony 2.6 you would use SecurityContext.
SecurityContext will be deprecated in Symfony 3.0 in favour of the AuthorizationChecker.

For Symfony 2.6+ & Symfony 3.0 use AuthorizationChecker.


Symfony 2.5 (and below)

if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
    # User is a ROLE_ADMIN
}

Symfony 2.6 (and above)

if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
    # User is a ROLE_ADMIN
}

Similar Question: How to check if an user is logged in Symfony2 inside a controller?

Read more the docs here: AuthorizationChecker


Are you in the controller for the page? If so, use the isGranted method of the security context: Access Controls for Controllers

Tags:

Php

Symfony