-1

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?

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

2 Answers2

1

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

Igor Pantović
  • 9,107
  • 2
  • 30
  • 43
1

I allow or not some actions.

If you mean regular actions in Controllers, then handy shortcut is to use @Security annotation from SensioFrameworkExtraBundle.

/**
 * @Security("has_role('ROLE_ADMIN')")
 */
public function indexAction()
{
    // ...
}

But, this is not really way how you should develop roled based actions in Symfony 2. You can define it in access_control.

# app/config/security.yml
security:
    # ...
    access_control:
        - { path: ^/admin/users, roles: ROLE_SUPER_ADMIN }
        - { path: ^/admin, roles: ROLE_ADMIN }
s7anley
  • 2,408
  • 22
  • 17
  • That's another way but if I've 500 controllers then I'll have 500 lines on the `security.yml` and is not the idea, I prefer to relay this on annotations. In the other side I'll check the ROLE for other conditional not for the complete function, anyway thanks – ReynierPM Nov 03 '14 at 23:02