简体   繁体   English

Symfony 2中的角色分配

[英]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 例如,在数据库中,我得到以下结果a:1:{i:0;s:11:"ROLE_DRIVER";} ,但是当我在应用程序中的某个位置尝试执行此操作

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

I always get false. 我总是假的。 In profiler I see that current user has ROLE_USER instead of _DRIVER . 在事件探查器中,我看到当前用户具有ROLE_USER而不是_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... 一切正常,但在Controller中...

I would recommend to do this for assigning the ROLE_DRIVER 我建议这样做以分配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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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