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?
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:
401
code, and let the frontend handle it.401
response, in CommenceEntryPoint.commence()
just use response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
instead of response.sendRedirect()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With