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?
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);
}
}
}
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