From f3c02dd603ffa461e4b8fa6e9eb16b17bcc8c2ec Mon Sep 17 00:00:00 2001 From: Peter Rehm Date: Thu, 31 Jul 2014 22:28:37 +0200 Subject: [PATCH] Fixed description for session storage --- cookbook/security/api_key_authentication.rst | 47 +++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/cookbook/security/api_key_authentication.rst b/cookbook/security/api_key_authentication.rst index 1965847c009..0add181f1c0 100644 --- a/cookbook/security/api_key_authentication.rst +++ b/cookbook/security/api_key_authentication.rst @@ -232,7 +232,7 @@ you can use to create an error ``Response``. class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface { - //... + // ... public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { @@ -427,6 +427,51 @@ configuration or set it to ``false``: ), )); +Even though the token is being stored in the session, the credentials - in this +case the API key (i.e. ``$token->getCredentials()``) - are not stored in the session +for security reasons. To take advantage of the session, update ``ApiKeyAuthenticator`` +to see if the stored token has a valid User object that can be used:: + + // src/Acme/HelloBundle/Security/ApiKeyAuthenticator.php + // ... + + class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface + { + // ... + public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) + { + $apiKey = $token->getCredentials(); + $username = $this->userProvider->getUsernameForApiKey($apiKey); + + // User is the Entity which represents your user + $user = $token->getUser(); + if ($user instanceof User) { + return new PreAuthenticatedToken( + $user, + $apiKey, + $providerKey, + $user->getRoles() + ); + } + + if (!$username) { + throw new AuthenticationException( + sprintf('API Key "%s" does not exist.', $apiKey) + ); + } + + $user = $this->userProvider->loadUserByUsername($username); + + return new PreAuthenticatedToken( + $user, + $apiKey, + $providerKey, + $user->getRoles() + ); + } + // ... + } + Storing authentication information in the session works like this: #. At the end of each request, Symfony serializes the token object (returned