Symfony security returns 401 response instead of redirect

I am writing an ajax application with ajax authentication, and now I started using the symfony security component in silex to handle authentication / authorization.
Performing a simple test with a simple configuration, I go to the protected zone using a firewall and the answer I get is redirected to the /login page, but what I need in my application is answer 401 with possible additional information (in headers or json body) on how to log in.

 $app['security.firewalls'] = [ 'api' => [ 'pattern' => '^/api', 'logout' => ['logout_path'=>'/auth/logout'], 'users' => $app->share(function(Application $app) { return new MyUserProvider(); }) ] ]; 

EDIT: I have a hint, but I'm not sure how to use it. Implementing an entry point using AuthenticationEntryPointInterface I can tell the api how to respond to unauthorized requests and provide the user with the instructions necessary for authentication. This may be my 401 answer with login instructions.

+8
security authentication php symfony silex
source share
2 answers

You need an AuthenticationEntryPoint handler. A simple example:

 class AuthenticationEntryPoint implements AuthenticationEntryPointInterface { /** * Starts the authentication scheme. * * @param Request $request The request that resulted in an AuthenticationException * @param AuthenticationException $authException The exception that started the authentication process * * @return Response */ public function start(Request $request, AuthenticationException $authException = null) { $array = array('success' => false); $response = new Response(json_encode($array), 401); $response->headers->set('Content-Type', 'application/json'); return $response; } } 

Register the class as a service in the services.xml file:

 <parameters> <parameter key="authentication_entry_point.class">YourNameSpace\AuthenticationEntryPoint</parameter> </parameters> <services> <service id="authentication_entry_point" class="%authentication_entry_point.class%"/> </services> 

and make a small change to the security.yml file:

 security: firewalls: somename: entry_point: authentication_entry_point 
+4
source share

I was able to override the default entry point for the "form" type in the "api" firewall as follows:

 $app['security.entry_point.api.form'] = $app->share(function () use ($app) { return new MyAuthenticationEntryPoint(); }); 

Then this is just a matter of implementing AuthenticationEntryPointInterface:

http://symfony.com/doc/current/components/security/firewall.html#entry-points

Take a look at the symfony implementation to get an idea:

 Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint 

Also, it might be worth checking out the silex security provider to see how they embed this in "security.entry_point.form._proto" by default.

 Silex\Provider\SecurityServiceProvider 
+1
source share

All Articles