13

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 ?

Aritz
  • 30,971
  • 16
  • 136
  • 217
abiieez
  • 3,139
  • 14
  • 57
  • 110
  • I think this link may help [Handle unauthorized error message for Basic Authentication in Spring Security](http://stackoverflow.com/questions/4397062/handle-unauthorized-error-message-for-basic-authentication-in-spring-security) – Dino Tw Sep 03 '13 at 15:22
  • See also: http://stackoverflow.com/questions/23739746/howto-configure-spring-security-to-return-403-for-rest-urls-and-redirect-to-logi – yankee Jan 09 '15 at 15:25

2 Answers2

0

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");                    
    }
0

You can also solve this by using a DelegatingAuthenticationEntryPoint. You can use any RequestMatcher based on your app to delegate the control to another AuthenticationEntryPoint, based on an HTTP header (like in your case), path prefix or any other identifier.

For example, if your REST API has the "/api" prefix:

@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>();
    entryPoints.put(new AntPathRequestMatcher("/api/**"), new Http403ForbiddenEntryPoint());
    DelegatingAuthenticationEntryPoint defaultEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
    defaultEntryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
    return defaultEntryPoint;
}
aminits
  • 174
  • 4