0

我正在尝试构建一个登录服务,将身份验证令牌设置为 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'));

我的工作有什么明显的问题吗?

4

1 回答 1

1

示例:

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
    ));
}
于 2013-07-30T06:22:38.753 回答