简体   繁体   中英

Roles assignement in Symfony 2

I try to assign role to user in my controller. For example in database I getting this result a:1:{i:0;s:11:"ROLE_DRIVER";} , but when somewhere in my app I try do this

if ($securityContext->isGranted('ROLE_DRIVER')) {

I always get false. In profiler I see that current user has ROLE_USER instead of _DRIVER . Where is my problem ? Here is my role assign:

$user->setRoles(array(1 => 'ROLE_DRIVER'));

User config:

# FOSUserBundle configuration
fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: Vputi\UserBundle\Entity\User
    registration:
            form:
                type: vputi_user_registration
    profile:
            form:
                type: vputi_user_profile
    change_password:
             form:
                type: vputi_user_change_password
                name: vputi_user_change_password

When in twig I do this:

{% if user.roles[0] == 'ROLE_DRIVER' %}

All works fine, but in Controller...

I would recommend to do this for assigning the ROLE_DRIVER

$user->addRole('ROLE_DRIVER');

Or you can change the way you are giving it a value to:

$user->setRoles(array("ROLE_DRIVER"));
//update user 

Updates:

$user->addRole('ROLE_DRIVER');
$user->addRole('ROLE_OLD_DRIVER');

this is the same as setting this two roles in one line:

$user->setRoles(array("ROLE_DRIVER", "ROLE_OLD_DRIVER"));

Twig checks:

{% if app.user.hasRole('ROLE_FOO') %}
    ...
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM