dqvtm82066 2014-10-28 13:11 采纳率: 0%
浏览 46
已采纳

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...

  • 写回答

1条回答 默认 最新

  • dpfl37651 2014-10-28 13:18
    关注

    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 %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题