Symfony 令牌 getCredentials returns 空

Symfony token getCredentials returns null

我创建了一种使用 API 密钥对用户进行身份验证的方法,这要归功于 class A 实现了 SimplePreAuthenticatorInterface 接口。一切正常(用户已成功通过身份验证)。

我正在尝试存储 API 密钥,以供用户以后在旅途中使用。为此,在我的 class A 的身份验证方法中,我 return 一个 PreAuthenticatedToken,其中凭据是我的 API 密钥。

问题是:在自定义服务中,当我尝试获取令牌凭据时,我得到 null... 当我评论第 76 行时,我成功获取了 API 键PreAuthenticatedToken Symfony 核心 class :

public function eraseCredentials()
{
    parent::eraseCredentials();
    //$this->credentials = null;
}

我的问题是:
1) 为什么调用方法eraseCredentials,而用户已通过身份验证?我以为这个方法是在用户注销时调用的...
2)我做错了什么? PreAuthenticatedToken 令牌是否适合存储我的 API 密钥?我怎样才能从定制服务中取回它们?

谢谢你帮助我。 :)

PS :我是一个在 Whosebug 发帖的新手(和英文 ^^)。如有任何错误,请提前致歉。

我找到了 another similar question,但它没有帮助响应,我添加了更多精确度。

编辑:我尝试获取凭据的自定义服务代码是:

$token = $this->container->get("security.token_storage")->getToken();
if ($token !== null) {
  $credentials = $token->getCredentials();
  // $credentials is null here
}

编辑 2SimplePreAuthenticatorInterface::authenticateToken 方法代码中的 return 部分:

return new PreAuthenticatedToken(
    $user,
    $apiKeys,
    $providerKey,
    $user->getRoles()
);

广告 1。这取决于您的 AuthenticationProviderManager:此 class 接受 $eraseCredentials 作为第二个参数 - 默认设置为 true (here) .

这就是为什么在 PreAuthenticatedToken $token 上调用 eraseCredentials 方法的原因(here)。

广告 2。请查看 How to Authenticate Users with API Keys 教程。您应该创建自定义 ApiKeyAuthenticator class 并在其中添加逻辑。

根据您的评论:

请注意,教程中的 authenticateMethod 是在 authenticate 方法(here). At that time token credentials are not erased yet and you can access them. For security reason they are erased after authentication (but this can also be changed / configured via security.yml 文件)中调用的。如果您以后需要它们,您可以引入自定义令牌 class 并在那里存储 API 密钥。