@@ -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+
430475Storing 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