简体   繁体   English

Symfony2角色/组-is_granted未检测到用户具有的角色

[英]Symfony2 roles/groups - is_granted is not detecting roles that the user has

I have followed the 'How to load Security Users from the Database (the Entity Provider)' recipe from the Symfony2 cook book (http://symfony.com/doc/current/cookbook/security/entity_provider.html), except I am not using the Custom Entity Provider - which means my User class is using lazy loading for the roles. 我遵循Symfony2烹饪手册(http://symfony.com/doc/current/cookbook/security/entity_provider.html)中的“如何从数据库(实体提供者)加载安全用户”食谱,但我不使用自定义实体提供程序-这意味着我的User类正在为角色使用延迟加载。

The firewall/access control in the security all works fine. 安全性中的防火墙/访问控制一切正常。 I have some routes that only ROLE_ADMIN users can access and some that ROLE_USER users can access - these work fine. 我有一些仅ROLE_ADMIN用户可以访问的路由,有些ROLE_USER用户可以访问的路由-这些工作正常。

The problem is that in my base template, I have a bar that is displayed like: 问题是在我的基本模板中,我有一个显示如下的栏:

<p>Logged in as: {{ app.user.username }} {% if is_granted('ROLE_ADMIN') %}| <a href="{{ path('bassettprovidentia_skeleton_admindashboard') }}">Admin area</a> {% endif %}| <a href="#">Settings</a> | <a href="{{ path('bassettprovidentia_skeleton_logout') }}">Log out</a></p>

Even though my user has the ROLE_ADMIN role in the database (and can access URLs that are restricted to that role), the "Admin area" link is not being displayed! 即使我的用户在数据库中具有ROLE_ADMIN角色(并且可以访问受限于该角色的URL),也不会显示“管理区域”链接!

In the same form, I have this: 以相同的形式,我有这个:

<p>Roles: {% for role in app.user.roles %}{{ role.name }} [{{ role.role }}]{% if not loop.last %}, {% endif %}{% endfor %}</p>

It works fine! 工作正常! All of the roles which the user has are displayed! 显示用户拥有的所有角色!

What am I doing wrong? 我究竟做错了什么?

Is the lazy-loading to blame? 懒加载是罪魁祸首吗?

It isn't causing problem's elsewhere. 它不会引起其他问题。

Okay - I found the answer. 好的-我找到了答案。 I can't beleive how obvious it was. 我无法相信它有多明显。

The user roles taken from the app.user object (ie, the second snippet) are obviously taken from the database as and when I request them. 当我请求它们时,从app.user对象(即第二个片段)中获取的用户角色显然是从数据库中获取的。

The is_granted() call obviously uses the session to see what roles a user has. is_granted()调用显然使用该会话来查看用户具有哪些角色。 I had been playing around and changing roles whilst forgetting to log out and in again - no wonder certain roles weren't showing. 我一直在玩耍并更换角色,却忘记了注销并再次登录-难怪某些角色没有出现。

After logging in and out and playing around with different roles, I can confirm it all works fine. 登录和注销并使用不同的角色后,我可以确认一切正常。

If I hadn't of taken a break and come back this morning, I might have been chasing myself in circles for hours; 如果我不休息片刻再回到今天早上,那我可能已经在圈子里追逐自己几个小时了。 there's a lesson to be learned there. 那里有一个教训要学习。

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

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