简体   繁体   English

Symfony中的动态角色

[英]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. 我试图使用事件监听器来做到这一点,但是它只是为那个http请求添加了动态角色。

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)? 这里有一个类似的问题: 如何在使用symfony2(和fosUserBundle)登录时动态添加用户角色?

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

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