'Spring Security Authentication Entry Point
I have enabled Rest support on my Spring MVC application with setting up AuthenticationEntryPoint on my security-context.xml as
<http auto-config="false" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="restAuthenticationEntryPoint">
The RestAuthenticationEntryPoint.java
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
Whenever any user tries to access resources without authenticating it will give the following error:
HTTP Status 401 - Unauthorized
The above behaviour is correct only for Rest services. However I would like to have the default behaviour which redirect user to login page for normal web request if the user hasn't been authenticated. How to achieve this ?
Solution 1:[1]
I have implemented this by sending HTTP Header in API request and send response according to that header from commence method of AuthenticationEntryPoint
You can implement this by adding below code to commence method:
if(request.getHeader("request-source") != null && request.getHeader("request-source").equals("API")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}else {
response.sendRedirect("/login");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shahnavaz Saiyad |
