Symfony2 security - disable login and show ban

I am trying to prevent redirection to the login page when the user tries to access the page without a token, I have a single page application and I just put ajax requests under the firewall and when the user does ajax without a token, I want ajax to return a forbidden exception so I can catch it on the client side

ajax is currently returning "Found" as the request is redirected to the login page

I have not found a solution in the cookbook so far, I do not want to use api tokens, send an exception instead of redirecting to login

+6
source share
1 answer

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

When the user is not authenticated at all (that is, when the token store does not yet have a token), the firewall entry point will be called to β€œstart” the authentication process. The entry point must implement AuthenticationEntryPointInterface, which has only one method: start (). This method receives the current Request object and the exception from which the exception listener was called. The method should return a Response object. This could be, for example, a page containing a login form or, in the case of basic HTTP authentication, a response with a WWW-Authenticate heading that will prompt the user to provide their username and password.

So, to do this, you need to create a class that will 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 

Finally, pass the service.entry_point service identifier to entry_point in the firewall section of the security.yml file.

That should do the trick.

+7
source

Source: https://habr.com/ru/post/989868/


All Articles