@@ -37,6 +37,7 @@ value and then a User object is created::
3737 use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
3838 use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
3939 use Symfony\Component\Security\Core\Exception\AuthenticationException;
40+ use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
4041 use Symfony\Component\Security\Core\Exception\BadCredentialsException;
4142 use Symfony\Component\Security\Core\User\UserProviderInterface;
4243 use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
@@ -80,7 +81,9 @@ value and then a User object is created::
8081 $username = $userProvider->getUsernameForApiKey($apiKey);
8182
8283 if (!$username) {
83- throw new AuthenticationException(
84+ // CAUTION: this message will be returned to the client
85+ // (so don't put any un-trusted messages / error strings here)
86+ throw new CustomUserMessageAuthenticationException(
8487 sprintf('API Key "%s" does not exist.', $apiKey)
8588 );
8689 }
@@ -101,6 +104,11 @@ value and then a User object is created::
101104 }
102105 }
103106
107+ .. versionadded :: 2.8
108+ The ``CustomUserMessageAuthenticationException `` class is new in Symfony 2.8
109+ and helps you return custom authentication messages. In 2.7 or earlier, throw
110+ an ``AuthenticationException `` or any sub-class (you can still do this in 2.8).
111+
104112Once you've :ref: `configured <cookbook-security-api-key-config >` everything,
105113you'll be able to authenticate by adding an apikey parameter to the query
106114string, like ``http://example.com/admin/foo?apikey=37b51d194a7513e45b56f6524f2d51f2 ``.
@@ -291,7 +299,11 @@ you can use to create an error ``Response``.
291299
292300 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
293301 {
294- return new Response("Authentication Failed.", 403);
302+ return new Response(
303+ // this contains information about *why* authentication failed
304+ // use it, or return your own message
305+ strtr($exception->getMessageKey(), $exception->getMessageData())
306+ , 403)
295307 }
296308 }
297309
@@ -543,7 +555,8 @@ to see if the stored token has a valid User object that can be used::
543555 }
544556
545557 if (!$username) {
546- throw new AuthenticationException(
558+ // this message will be returned to the client
559+ throw new CustomUserMessageAuthenticationException(
547560 sprintf('API Key "%s" does not exist.', $apiKey)
548561 );
549562 }
0 commit comments