我正在尝试构建一个登录服务,该服务设置身份验证令牌,因为cookie会将其发送给响应中的用户。虽然看起来我似乎无法验证用户身份。我的代码中是否缺少某些内容?
public function login(Response $response,User $user, $roles)
{
// The name of my firewall is 'secured_area'
$firewall = 'secured_area';
// Build usernamepasswordtoken. I'm not really certain what to set the credentials
// but in all the examples I've seen this field set to null. roles is an array of
// of string names for roles. I'm simply passing in array('ROLE_USER') into $roles.
// The $user is actually a user entity that should get serialized with the token.
$token = new UsernamePasswordToken($user, null, $firewall, $roles);
// set the session string name and serialize my token.
$this->session->set('_security_'.$firewall, serialize($token));
$this->session->save();
// make new cookie and send it off to the client
$cookie = new Cookie($this->session->getName(), $this->session->getId());
$response->headers->setCookie($cookie);
return $response;
}
// In my controller I simply do
return login(new Response("work"), $user, array('ROLE_USER'));
我的工作有什么明显的错误吗?
答案 0 :(得分:1)
Examlpe:
public function loginAction()
{
$request = $this->getRequest();
$csrfToken = $this->container->has('form.csrf_provider')
? $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate')
: null;
if ($this->get('security.context')->isGranted('ROLE_USER'))
{
return $this->redirect($this->generateUrl('homepage'));
}
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$session = $request->getSession();
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
if ($error) {
$error = $error->getMessage();
}
$lastUsername = (null === $session) ? '' : $request->getSession()->get(SecurityContext::LAST_USERNAME);
$form = $this->createForm('form_login')->createView();
return $this->render('AcmeTestBundle:User:login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
'csrf_token' => $csrfToken,
'form' => $form
));
}