Reputation: 1203
For my web service using FOSRestBundle, I created a firewall that forces a login to access the application.
My problem is that when I make a call to the API via ajax, I need to get the error code 401 when the user is not authenticated rather than receive the html source code of the login form. How do I configure the application?
secured_area:
pattern: ^/
form_login:
provider: fos_userbundle
use_forward: false
default_target_path: /w
logout:
path: /logout
target: /login
EDIT:
Thanks to Ryan here is the KernelExceptionListener method.
public function onKernelException( GetResponseForExceptionEvent $event ) {
// get exception
$exception = $event->getException();
// get path
$path = $event->getRequest()->getPathInfo();
if ( $exception instanceOf AuthenticationException && ($event->getRequest()->isXmlHttpRequest() || strpos( $path, '/api' ) === 0) ) {
$response = new Response();
$response->setStatusCode( 401 );
$event->setResponse( $response );
$event->stopPropagation();
}
}
Upvotes: 3
Views: 1486
Reputation: 6642
You used the word authentication and not authorization and unfortunately this does not seem to be already written. Therefore, you will probably need to create your own.
In the generic case, a simple Kernel Event listener to intercept the AuthenticationException exception should be created. Capturing this event should allow you to perform any action you like before the redirect to the login page.
The FOSRestBundle should provide a good example of how to do this. The FOSRestBundle provides this functionality for the authorization layer currently (AccessDeniedException). With a little bit of modification the same framework should provide the capability to do the same for the authentication layer as well.
See pull #308 for the change set that provides the authorization listeners. See Security Exception Listener for documentation on how to configure the listeners.
Upvotes: 2