phpsymfonysecurity-context

How do I check if a user has certain role and therefore allow some actions?


I need to check if logged in user has certain roles on the system so I allow or not some actions. I'm using JMSSecurityExtraBundle and I check the docs for Expression Based Authorization but I'm doing something wrong since code is not working. Take a look to this code:

use JMS\SecurityExtraBundle\Annotation\Secure;
use JMS\SecurityExtraBundle\Security\Authorization\Expression\Expression;

if ($this->get('security.context')->isGranted(array(new Expression('hasRole("ROLE_ADMIN")')))) {
    echo "Enter";
} else {
    echo "Do not enter";
}

But any time I logged in, even as ADMIN which have all the rights and has ROLE_ADMIN, the only text I'm seeing is "Do not enter" which is totally wrong. In the example code as explain in here the author use a $securityContext var but where it comes from? Where this var is defined? I assume that it will point to SecurityContext but I'm not so sure so, where is the problem on my code? How do I check if user has certain role and therefore allow it to execute some code or not?


Solution

  • You don't need any usage of annotation expressions if you just want to check user's roles in controller, this is sufficient:

    if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
        echo "Enter";
    } else {
        echo "Do not enter";
    }
    

    One quick search on google would have returned you documentation section about that right away: http://symfony.com/doc/current/book/security.html#access-control