Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid redirecting to login form for some URL with Spring Security?

This is the Spring Security configuration of my webapp

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", LOGIN, "/webjars/**").permitAll()
            .antMatchers(CONFIGURATION).hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
            .antMatchers("/api/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
            .and()
        .formLogin()
            .loginPage(LOGIN)
            .and()
        .addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class);
}

Currently the server is redirecting to the LOGIN page every request that does not have the right credentials.

I want to redirect to the LOGIN page only the unauthorized requests to CONFIGURATION, while the unauthorized requests to /api/** should answer with 403.

What's a good way of achieving that?

like image 204
Michele Da Ros Avatar asked Jul 11 '17 09:07

Michele Da Ros


1 Answers

I solved my problem using an AuthenticationEntryPoint:

http
    .authorizeRequests()
        .antMatchers(LOGIN).permitAll()
        .antMatchers("/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
        .and()
    .addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class)
    .exceptionHandling().authenticationEntryPoint(unauthenticatedRequestHandler);
@Bean
UnauthenticatedRequestHandler unauthenticatedRequestHandler() {
    return new UnauthenticatedRequestHandler();
}

static class UnauthenticatedRequestHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        if (request.getServletPath().startsWith("/api/")) {
            response.setStatus(403);
        } else {
            response.sendRedirect(LOGIN);
        }
    }
}
like image 96
Michele Da Ros Avatar answered Sep 27 '22 21:09

Michele Da Ros