eidsonator
eidsonator

Reputation: 1325

Symfony2 - Can I give an anonymous user a 'ROLE_SOMETHING'

I'm using the Symfony framework with the FOS User Bundle. I'm using the security context to determine which menu items and other items to display.

$securityContext = $this->get('security.context');
if ($securityContext->isGranted($report['Permission'])){
    //add the menu item...
}

Is there any way to give a anonymous user a security context of 'ROLE_USER'? I've got logged in users working properly.

I tried adding the line:

role_hierarchy:
    IS_AUTHENTICATED_ANONYMOUSLY: ROLE_USER

to my security.yml hoping this would do it, but apparently not. I've Googled around a little bit and read the documentation.

I imagine that:

if ($securityContext->isGranted($report['Permission'])
    || ($report['Permission'] === 'ROLE_USER' && $securityContext->is_anonymous()))

would work, but this feels like kind of a hack (and not very DRY)

Edit: This is for an intranet site. I've got a table that contains names of reports. Some reports should be able to be seen by everyone, regardless of if they are logged in or not. Some reports require permissions to view. I don't want to create several hundred users when only a handful will need access.

Upvotes: 1

Views: 1915

Answers (1)

Charles-Antoine Fournel
Charles-Antoine Fournel

Reputation: 1783

If you are trying to give access to people to a given url why not simply authorize it this way ?

You have 2 method to achieve this: create a firewall authorization or role defined a url

1) Firewall autorization

firewalls:
        test:
            pattern: ^/ws // you url or schema url with regex
            anonymous: true

2) url with a role defined access

access_control:
         - { path: ^/given-url, roles: IS_AUTHENTICATED_ANONYMOUSLY }


// in app/config/security.yml

in both case, non authenticated user and authenticated user will have access to this url

By the way , if you want to test (in order to display some user variables) if a user is authenticated or not , just make your test in twig

   {% if app.user is defined and app.user is not null %} 
       The user {{ app.user.username }} is connected.
   {% else %}
       No user connected
   {% end %}

EDIT : Content based view : juste create a route for your action which would not match your firewall rules

Upvotes: 1

Related Questions