我有以下身份验证处理程序:
class LoginAuthSuccessHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
private $router;
private $container;
/**
* Constructor
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router, $container)
{
$this->router = $router;
$this->container = $container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($request->isXmlHttpRequest()) {
$user = $this->container->get('security.context')->getToken()->getUser();
$result = array('success' => true, 'user' => $user);
return new Response(json_encode($result));
} else {
$route = $this->router->generate('ShopiousMainBundle_profile');
$referrer_url = $request->server->get('HTTP_REFERER');
if (strstr($referrer_url, '/items/')) {
$route = $referrer_url;
}
return new RedirectResponse($route);
}
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($request->isXmlHttpRequest()) {
$result = array('success' => false, 'message' => $exception->getMessage());
return new Response(json_encode($result));
} else {
// Handle non XmlHttp request here
}
}
}
为什么会这样:
$user = $this->container->get('security.context')->getToken()->getUser();
返回null?我如何在此时获得经过身份验证的用户?
答案 0 :(得分:4)
您应该使用您收到的$token
变量作为参数,而不是$this->container->get('security.context')->getToken()
。
$user = $token->getUser();
答案 1 :(得分:0)
maibe你没有在security.yml中设置你的提供者。
security:
provider:
example:
entity: {class Acme\AuctionBundle\Entity\User, property: username}
用您的替换Bundle和实体。
答案 2 :(得分:0)
我找到的唯一方法是注入entityManager,
calls:
- [setEntityManager,[@doctrine.orm.entity_manager]]
使用该用户名从请求中获取用户名并查询该用户。
$userRepo->findByEmail($request->get('_username'));
答案 3 :(得分:0)
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
}
这就是全部;)