@@ -25,6 +25,7 @@ value and then a User object is created::
2525 use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
2626 use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
2727 use Symfony\Component\Security\Core\Exception\AuthenticationException;
28+ use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
2829 use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
2930 use Symfony\Component\HttpFoundation\Request;
3031 use Symfony\Component\Security\Core\User\UserProviderInterface;
@@ -69,7 +70,8 @@ value and then a User object is created::
6970 $username = $userProvider->getUsernameForApiKey($apiKey);
7071
7172 if (!$username) {
72- throw new AuthenticationException(
73+ // this message will be returned to the client
74+ throw new CustomUserMessageAuthenticationException(
7375 sprintf('API Key "%s" does not exist.', $apiKey)
7476 );
7577 }
@@ -90,6 +92,11 @@ value and then a User object is created::
9092 }
9193 }
9294
95+ .. versionadded :: 2.8
96+ The ``CustomUserMessageAuthenticationException `` class is new in Symfony 2.8
97+ and helps you return custom authentication messages. In 2.7 or earlier, throw
98+ an ``AuthenticationException `` or any sub-class (you can still do this in 2.8).
99+
93100Once you've :ref: `configured <cookbook-security-api-key-config >` everything,
94101you'll be able to authenticate by adding an apikey parameter to the query
95102string, like ``http://example.com/admin/foo?apikey=37b51d194a7513e45b56f6524f2d51f2 ``.
@@ -280,7 +287,11 @@ you can use to create an error ``Response``.
280287
281288 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
282289 {
283- return new Response("Authentication Failed.", 403);
290+ return new Response(
291+ // this contains information about *why* authentication failed
292+ // use it, or return your own message
293+ strtr($exception->getMessageKey(), $exception->getMessageData())
294+ , 403)
284295 }
285296 }
286297
@@ -532,7 +543,8 @@ to see if the stored token has a valid User object that can be used::
532543 }
533544
534545 if (!$username) {
535- throw new AuthenticationException(
546+ // this message will be returned to the client
547+ throw new CustomUserMessageAuthenticationException(
536548 sprintf('API Key "%s" does not exist.', $apiKey)
537549 );
538550 }
0 commit comments