Symfony 2.8 Guard AbstractGuardAuthenticator,如何return一个真正的token?

Symfony 2.8 Guard AbstractGuardAuthenticator, how to return a real token?

我正在使用 Symfony 2.8 中添加的相对较新的 Guard 子系统中的 AbstractGuardAuthenticator

我的设置非常简单。我向受保护的 URL 发送请求,该请求采用 username:password base64 编码。它会根据数据库进行检查,并且应该 return 一个标记。

认证成功方法:

 public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        //If login successful, return token
        return new Response($this->tokenStorage->getToken());        
    }

return是什么:

 PostAuthenticationGuardToken(user="test", authenticated=true, roles="ROLE_ADVANCED,
 ROLE_USER")

现在,这就是我所期望的,因为 AbstractGuardAuthenticator 完全像这样定义了创建此令牌的方法。

public function createAuthenticatedToken(UserInterface $user, $providerKey)
    {
        return new PostAuthenticationGuardToken(
            $user,
            $providerKey,
            $user->getRoles()
        );
    }

更新 1.1:

使用 LexikJWTAuthenticationBundle 我现在正尝试将 Json Web 令牌实施到我的应用程序的 AbstractGuardAuthenticator 中。 Lexik 包提供了一个成功和失败的处理程序:lexik_jwt_authentication.handler.authentication_success & lexik_jwt_authentication.handler.authentication_failure 指向 类 将某些 JWT 变量注入其中。我如何将它们连接到 AbstractGuardAuthenticator 的成功和失败处理程序中?

 crud:
         anonymous: ~
         guard:
             authenticators:
                - app.token_authenticator
         pattern: ^/database/

以及Guard成功和失败方法

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    if ($token = $request->headers->get('X-AUTH-TOKEN')) {
        //on success, let the request continue
    } else {
        //If login successful, return token
        return new Response($this->tokenStorage->getToken());
    }
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, 403);
}

我目前正在扩展和合并 JWTTokenAuthenticator 与我自己的令牌验证器而不是 AbstractGuardAuthenticator 因为两者都实现 GuardAuthenticatorInterface.

I'd like to know how to return a real token, which can be used to authenticate a user instead of sending the username:password every time.

Symfony 防护组件

Guard旨在简化身份验证子系统。

在使用 Guard 之前,设置自定义身份验证的工作量要大得多。您需要创建多个 parts/classes 并使它们协同工作。它很灵活,您可以创建任何您想要的身份验证系统,但它需要一些努力。使用 Guard,它变得容易得多,同时保持所有灵活性。

不是您要查找的组件。

Symfony 安全令牌

在有关 Guard 组件的文档中阅读 "token" 一词时,所指的是 TokenInterface 的实现。 Symfony 使用这些实现来跟踪身份验证状态。这些实现永远不会离开您的应用程序,这是内部的事情。

不是您要查找的令牌。

JSON 网络令牌

您所说的 "token" 是客户端可以用来进行身份验证的一些信息。这可以是一个随机字符串,例如 OAuth 2.0 protocol, or a self-contained and signed set of information, like JSON Web Tokens (JWT) 的 "access token"。

恕我直言,JWT 将是目前最具前瞻性的代币。 The Anatomy of a JSON Web Token 是熟悉 JWT 的好书。

有几个包可以轻松地将 JWT 集成到您的 Symfony 项目中。 LexikJWTAuthenticationBundle 是目前最受欢迎的。我建议你看看:)