我不知道如何用用户的id来代替Symfony中的用户名来模拟用户?
以下使用用户名的技巧无法使用id,因为symfony正在寻找用户名:
?_switch_user={id}发布于 2016-06-23 14:26:38
如果不实现自己的防火墙侦听器,这是不可能的,因为它在幕后从用户提供程序(它的接口中只有一个loadUserByUsername()方法)加载用户。
但是,您可以实现自己的防火墙侦听器,并通过查看Symfony\Component\Security\Http\Firewall\SwitchUserListener中的代码获得灵感。有关实现您自己的身份验证提供程序的详细信息,请查看食谱文章。
编辑:
一个可能的解决方案可能是注册一个额外的请求侦听器:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LookupSwitchUserListener implements EventSubscriberInterface
{
private $repository;
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['lookup', 12] // before the firewall
];
}
public function lookup(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->has('_switch_user') {
return; // do nothing if already a _switch_user param present
}
if (!$id = $request->query->has('_switch_user_by_id')) {
return; // do nothing if no _switch_user_by_id param
}
// lookup $username by $id using the repository here
$request->attributes->set('_switch_user', $username);
}
}现在,在服务容器中注册此侦听器:
services:
my_listener:
class: LookupSwitchUserListener
tags:
- { name: kernel.event_subscriber }使用?_switch_user_by_id=xxx参数调用url现在应该正确地查找用户名并设置它,以便SwitchUserListener可以切换到指定的用户。
https://stackoverflow.com/questions/37994268
复制相似问题