Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 security - disable login path and show forbidden

i am trying to prevent redirect to login page when user is trying to access a page without token, i have single page app and i am only putting the ajax requests under firewall and when a user is doing ajax without token i want the ajax to return forbidden exception so i will be able to catch it in client side

currently the ajax returns "Found" since the request is being redirected to the login page

i haven't found a solution in cookbook so far i dont want to use api tokens, only send an exception instead of redirecting to login

like image 586
roy Avatar asked Jun 27 '15 21:06

roy


1 Answers

You need to define an entry_point to your firewall in order for you to return unauthorized response. Information about entry points can be found in the documentation here. I will copy the paragraph in case of future requests here.

When the user is not authenticated at all (i.e. when the token storage has no token yet), the firewall's entry point will be called to "start" the authentication process. An entry point should implement AuthenticationEntryPointInterface, which has only one method: start(). This method receives the current Request object and the exception by which the exception listener was triggered. The method should return a Response object. This could be, for instance, the page containing the login form or, in the case of Basic HTTP authentication, a response with a WWW-Authenticate header, which will prompt the user to supply their username and password.

So in order for you to do that, you have to create a class that is going to be defined as a service.

It should look like this:

namespace MyBundle\Service;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class CustomEntryPoint implements AuthenticationEntryPointInterface
{

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $response = new Response("", Response::HTTP_UNAUTHORIZED);

        return $response;
    }

}

And in your services.yml file

services:
    service.entry_point:
        class: MyBundle\Service\CustomEntryPoint

And finally pass the service id service.entry_point to your entry_point option in firewall section of security.yml file.

This should do the trick.

like image 170
Artamiel Avatar answered Sep 21 '22 01:09

Artamiel