Reputation: 33
I created a way to authenticate a user with API keys, thanks to a class A
implementing the SimplePreAuthenticatorInterface
interface. Everything works well (the user is successfully authenticated).
I'm trying to store the API keys, for a later use during the user's journey. To do so, inside the authenticate method of my class A
, I return a PreAuthenticatedToken
in which the credentials are my API keys.
The problem is : Inside a custom service, when I try to get the token credentials, I get null
... I successfully get the API keys when I comment the line 76 of the PreAuthenticatedToken
Symfony core class :
public function eraseCredentials()
{
parent::eraseCredentials();
//$this->credentials = null;
}
My questions are:
1) Why is the method eraseCredentials
called whereas the user is authenticated? I thought this method was called during user's logging out...
2) What am I doing wrong? Is the PreAuthenticatedToken
token the right place to store my API keys? How can I get them back from a custom service ?
Thanks for helping me. :)
PS : I'm a newbee on posting in Stackoverflow (and in English ^^). Sorry in advance for any mistakes.
I found another similar question but it has no helping response and I added some more precisions.
EDIT: The code of my custom service where I try to get the credentials is:
$token = $this->container->get("security.token_storage")->getToken();
if ($token !== null) {
$credentials = $token->getCredentials();
// $credentials is null here
}
EDIT 2: The return part in my code of my SimplePreAuthenticatorInterface::authenticateToken
method :
return new PreAuthenticatedToken(
$user,
$apiKeys,
$providerKey,
$user->getRoles()
);
Upvotes: 3
Views: 1059
Reputation: 3338
Ad 1. It depends on your AuthenticationProviderManager
: this class accepts $eraseCredentials
as second parameter - by default set to true
(here).
That's why eraseCredentials
method is being called on PreAuthenticatedToken
$token
during authenication (here).
Ad 2. Please check How to Authenticate Users with API Keys tutorial. You should create your custom ApiKeyAuthenticator
class and add logic there.
According to your comment:
Note that authenticateMethod
from tutorial is being called inside authenticate
method (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 file). If you need them later you can introduce custom token class and store API key there.
Upvotes: 1