如何模拟用户

编辑本页

警告:您正在浏览的文档欧宝体育电话<一个href="//www.oldmanjams.com/releases/2.7">欧宝娱乐app下载地址Symfony 2.7,现已不再维护。

读<一个href="//www.oldmanjams.com/doc/current/security/impersonating_user.html">本页的更新版本用于Sy欧宝娱乐app下载地址mfony 6.2(当前稳定版本)。

方法可以轻松地模拟用户switch_user防火墙侦听器:

  • YAML
  • XML
  • PHP
1 2 3 4 5 6 7 8
# app / config / security.yml安全:#……防火墙:主要:#……switch_user:真正的

要切换到另一个用户,只需使用_switch_user参数和用户名作为当前URL的值:

1
http://example.com/somewhere?_switch_user=thomas

若要切换回原始用户,请使用特殊_exit用户名:

1
http://example.com/somewhere?_switch_user=_exit

在模拟过程中,为用户提供了一个名为ROLE_PREVIOUS_ADMIN.例如,在模板中,此角色可用于显示退出模拟的链接:

  • 嫩枝
  • PHP
1 2 3
{%如果is_granted (ROLE_PREVIOUS_ADMIN) %}<一个href{{path('主页',{'_switch_user': '_exit'})}}>退出模拟一个>{%endif%}

在某些情况下,您可能需要获取表示模拟用户而不是模拟用户的对象。使用下面的代码片段遍历用户的角色,直到找到一个SwitchUserRole对象:

12 3 4 5 6 7 8 9 10 11 12 13
使用欧宝娱乐app下载地址组件安全核心角色SwitchUserRoleauthorizationChecker->get (“security.authorization_checker”);tokenStorage->get (“security.token_storage”);如果authorizationChecker->isGranted (“ROLE_PREVIOUS_ADMIN”)) {foreachtokenStorage->getToken ()->将getRoles ()作为角色){如果角色运算符SwitchUserRole) {impersonatorUser角色->getSource ()->getUser ();打破;}}}

当然,这个特性需要提供给一小部分用户。默认情况下,访问限制为具有ROLE_ALLOWED_TO_SWITCH的角色。方法修改此角色的名称角色设置。方法更改查询参数名称,以提高安全性参数设置:

  • YAML
  • XML
  • PHP
1 2 3 4 5 6 7 8
# app / config / security.yml安全:#……防火墙:主要:#……switch_user:角色:ROLE_ADMIN,参数:_want_to_be_this_user

security.switch_user事件。的<一个href="https://github.com/symfony/symfony/blob/2.7/src/Symfony/Component/Security/Http/Event/SwitchUserEvent.php" class="reference external" title="SwitchUserEvent"rel="external noopener noreferrer" target="_blank">SwitchUserEvent传递给侦听器,您可以使用它来获取您现在正在模拟的用户。

的<一个href="//www.oldmanjams.com/doc/2.7/session/locale_sticky_session.html" class="reference internal">在用户会话期间使区域设置“粘滞”当您模拟用户时,Article不会更新区域设置。下面的代码示例将展示如何更改粘性区域设置:

  • YAML
  • XML
  • PHP
1 2 3 4 5 6
# app / config / services.yml服务:app.switch_user_listener:类:AppBundle \ EventListener \ SwitchUserListener标签:-名称:kernel.event_listener,事件:security.switch_user,方法:onSwitchUser

谨慎

侦听器实现假设您的用户实体有一个getLocale ()方法:

12 3 4 5 6 7 8 9 10 11 12 13 14 15
/ / src / AppBundle / EventListener / SwitchUserListener.php名称空间AppBundleEventListener使用欧宝娱乐app下载地址组件安全Http事件SwitchUserEventSwitchUserListener公共函数onSwitchUser(SwitchUserEvent事件事件->getRequest ()->getSession ()->集(“_locale”事件->getTargetUser ()->getLocale ());}}

此工作,包括代码示例,是根据<一个rel="license" href="https://creativecommons.org/licenses/by-sa/3.0/">创作共用BY-SA 3.0许可证。