Skip to content

Commit 2b9cb7c

Browse files
committed
feature #4076 Fixed description of session storage of the ApiKeyAuthenticator (peterrehm)
This PR was submitted for the master branch but it was merged into the 2.4 branch instead (closes #4076). Discussion ---------- Fixed description of session storage of the ApiKeyAuthenticator | Q | A | ------------- | --- | Doc fix? | yes | New docs? | no | Applies to | 2.4 | Fixed tickets | #4060 I assume the authentication is needed for each request (even if token is stored in the session) since you can add custom logic in the authenticator. Commits ------- f3c02dd Fixed description for session storage
2 parents 8cbdf15 + 98aed88 commit 2b9cb7c

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

cookbook/security/api_key_authentication.rst

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ you can use to create an error ``Response``.
232232
233233
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
234234
{
235-
//...
235+
// ...
236236
237237
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
238238
{
@@ -427,6 +427,51 @@ configuration or set it to ``false``:
427427
),
428428
));
429429
430+
Even though the token is being stored in the session, the credentials - in this
431+
case the API key (i.e. ``$token->getCredentials()``) - are not stored in the session
432+
for security reasons. To take advantage of the session, update ``ApiKeyAuthenticator``
433+
to see if the stored token has a valid User object that can be used::
434+
435+
// src/Acme/HelloBundle/Security/ApiKeyAuthenticator.php
436+
// ...
437+
438+
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface
439+
{
440+
// ...
441+
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
442+
{
443+
$apiKey = $token->getCredentials();
444+
$username = $this->userProvider->getUsernameForApiKey($apiKey);
445+
446+
// User is the Entity which represents your user
447+
$user = $token->getUser();
448+
if ($user instanceof User) {
449+
return new PreAuthenticatedToken(
450+
$user,
451+
$apiKey,
452+
$providerKey,
453+
$user->getRoles()
454+
);
455+
}
456+
457+
if (!$username) {
458+
throw new AuthenticationException(
459+
sprintf('API Key "%s" does not exist.', $apiKey)
460+
);
461+
}
462+
463+
$user = $this->userProvider->loadUserByUsername($username);
464+
465+
return new PreAuthenticatedToken(
466+
$user,
467+
$apiKey,
468+
$providerKey,
469+
$user->getRoles()
470+
);
471+
}
472+
// ...
473+
}
474+
430475
Storing authentication information in the session works like this:
431476

432477
#. At the end of each request, Symfony serializes the token object (returned

0 commit comments

Comments
 (0)