0

我想在每个请求上检查用户实体的某些内容,如果满足某些条件,我想执行重定向。试过这个:

public static function getSubscribedEvents()
{
    return [
        KernelEvents::REQUEST => [
            ['watcher', 0],
        ]
    ];
}

public function watcher(GetResponseEvent $event)
{
    if (!$event->isMasterRequest()) return;

    /** @var Request $request */
    $request = $event->getRequest();
    echo "User: " . $request->getUser();
    exit();
}

但是 $request->getUser() 返回 null

有什么建议如何让用户参与内核事件?

4

1 回答 1

2

$request->getUser() does not return a user object that has been authenticated by the security component, but rather the username part of the HTTP basic auth.

For example, if you request http://username:password@example.com/ then $request->getUser() will contain "username".

To get the user object you have to inject the security.token_storage service into your event subscriber and then call $tokenStorage->getToken()->getUser().

Note that both getToken() and getUser() can return null, so you should check both first. Have a look at the getUser() implementation in Symfony's ControllerTrait on how best to do that.

于 2018-01-08T20:56:43.403 回答