Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

symfony

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.

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.

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!

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.

like image 220
Lewis Bassett Avatar asked Apr 17 '12 15:04

Lewis Bassett


1 Answers

Okay - I found the answer. I can't beleive how obvious it was.

The user roles taken from the app.user object (i.e., the second snippet) are obviously taken from the database as and when I request them.

The is_granted() call obviously uses the session to see what roles a user has. 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.

like image 84
Lewis Bassett Avatar answered Oct 20 '22 22:10

Lewis Bassett