简体   繁体   中英

Dynamic roles in symfony

I have been trying to assign dynamic roles to users in my application. I tried to use an event listener to do that, but it just added the dynamic role for that one http request.

This is the function in my custom event listener that adds the role.

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {

    $user = $this->security->getToken()->getUser();

    $role = new Role;
    $role->setId('ROLE_NEW');
    $user->addRole($role);
}

But I am not sure if this is even possible to do with event listeners. I just need to find a nice way how to add the roles for the whole time the user is logged. I would appreciate any help and suggestions.

I haven't tested this yet, but reading the cookbook this could work.

This example is a modified version of the example in the cookbook to accomodate for your requirements.

class DynamicRoleRequestListener
{
    public function __construct($session, $security)
    {
        $this->session = $session;
        $this->security = $security;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            // don't do anything if it's not the master request
            return;
        }

        if ($this->session->has('_is_dynamic_role_auth') && $this->session->get('_is_dynamic_role_auth') === true) {
            $role = new Role("ROLE_NEW"); //I'm assuming this implements RoleInterface
            $this->security->getRoles()[] = $role; //You might have to add credentials, too.
            $this->security->getUser()->addRole($role);
        }

        // ...
    }

    private $session;
    private $security;
}

And then you declare it as a service.

services:
    kernel.listener.dynamicrolerequest:
        class: Your\DemoBundle\EventListener\DynamicRoleRequestListener
        arguments: [@session, @security.context]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

A similar question is here: how to add user roles dynamically upon login with symfony2 (and fosUserBundle)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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