Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security: Redirect to Login Page in case of 401

I have an application that exposes a REST API and is secured using Spring Security. Is there a way to automatically redirect the client (from the server side) to the login page if a request sent to my server results in 401 - unauthorised?

like image 715
Samantha Catania Avatar asked Sep 04 '15 09:09

Samantha Catania


1 Answers

For spring-security application based on spring-boot.

Define a handler bean:

@Component
public class CommenceEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = 565662170056829238L;

    // invoked when user tries to access a secured REST resource without supplying any credentials,
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // send a json object, with http code 401,
        // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

        // redirect to login page, for non-ajax request,
        response.sendRedirect("/login.html");
    }
}

In security config class (e.g WebSecurityConfig):

Autowire the bean:

@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,

Specify handler:

.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,

Tips:

  • This is suitable only for non-ajax request,
  • For ajax request, better return 401 code, and let the frontend handle it.
    If you want to use 401 response, in CommenceEntryPoint.commence() just use response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); instead of response.sendRedirect().
like image 117
user218867 Avatar answered Nov 15 '22 06:11

user218867