@@ -25,6 +25,7 @@ value and then a User object is created::
25
25
use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
26
26
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
27
27
use Symfony\Component\Security\Core\Exception\AuthenticationException;
28
+ use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
28
29
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
29
30
use Symfony\Component\HttpFoundation\Request;
30
31
use Symfony\Component\Security\Core\User\UserProviderInterface;
@@ -69,7 +70,8 @@ value and then a User object is created::
69
70
$username = $userProvider->getUsernameForApiKey($apiKey);
70
71
71
72
if (!$username) {
72
- throw new AuthenticationException(
73
+ // this message will be returned to the client
74
+ throw new CustomUserMessageAuthenticationException(
73
75
sprintf('API Key "%s" does not exist.', $apiKey)
74
76
);
75
77
}
@@ -90,6 +92,11 @@ value and then a User object is created::
90
92
}
91
93
}
92
94
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
+
93
100
Once you've :ref: `configured <cookbook-security-api-key-config >` everything,
94
101
you'll be able to authenticate by adding an apikey parameter to the query
95
102
string, like ``http://example.com/admin/foo?apikey=37b51d194a7513e45b56f6524f2d51f2 ``.
@@ -280,7 +287,11 @@ you can use to create an error ``Response``.
280
287
281
288
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
282
289
{
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)
284
295
}
285
296
}
286
297
@@ -532,7 +543,8 @@ to see if the stored token has a valid User object that can be used::
532
543
}
533
544
534
545
if (!$username) {
535
- throw new AuthenticationException(
546
+ // this message will be returned to the client
547
+ throw new CustomUserMessageAuthenticationException(
536
548
sprintf('API Key "%s" does not exist.', $apiKey)
537
549
);
538
550
}
0 commit comments