@@ -232,7 +232,7 @@ you can use to create an error ``Response``.
232
232
233
233
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
234
234
{
235
- //...
235
+ // ...
236
236
237
237
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
238
238
{
@@ -427,6 +427,51 @@ configuration or set it to ``false``:
427
427
),
428
428
));
429
429
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
+
430
475
Storing authentication information in the session works like this:
431
476
432
477
#. At the end of each request, Symfony serializes the token object (returned
0 commit comments