Customizing Failure Handling

Authentication can fail inside your authenticator in any of these 3 functions:

  • getCredentials()
  • getUser()
  • checkCredentials()

The Customizing Authentication Failure Messages tutorial tells you how you can fail authentication and how to customize the error message when that happens.

But if you need more control, use the onAuthenticationFailure() method.

onAuthenticationFailure()

Every authenticator has a onAuthenticationFailure() method. This is called whenever authentication fails, and it has one job: create a Response that should be sent back to the user. This could be a redirect back to the login page or a 403 JSON response.

If you extend certain authenticators - like AbstractFormLoginAuthenticator - then this method is filled in for you automatically. But you can feel free to override it and customize.

Sending back JSON for AJAX

Suppose your login form uses AJAX. Instead of redirecting to /login on a failure, you probably want it to return some sort of JSON response. Just override onAuthenticationFailure():

98 lines src/AppBundle/Security/FormLoginAuthenticator.php
... lines 1 - 7
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
... line 10
use Symfony\Component\Security\Core\Exception\AuthenticationException;
... lines 12 - 16
class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
... lines 19 - 70
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
// AJAX! Maybe return some JSON
if ($request->isXmlHttpRequest()) {
return new JsonResponse(
// you could translate the message
array('message' => $exception->getMessageKey()),
403
);
}
// for non-AJAX requests, return the normal redirect
return parent::onAuthenticationFailure($request, $exception);
}
... lines 85 - 96
}

That's it! If you fail authentication via AJAX, you'll receive a JSON response instead of the redirect.

Leave a comment!