In Spring Boot web application I have the following security configuration:
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers().frameOptions().disable()
.and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasAuthority(Authority.Type.ROLE_ADMIN.getName())
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error").permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// @formatter:on
}
Right now, when I'm trying to access the example url /api/v1.0/user
, it redirects me to the /api/login
page.
How to configure this in order to return 403 Forbidden
instead of redirect to login page ?
This is a community Answer:
Problem:
Forbidden urls were returning the login page content (instead of a 403 status code).
I Had this code:
...
http.authorizeRequests().antMatchers("/uri/**").hasAuthority("SOME_ROLE");
Changed with Tong's suggestion:
...
http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
http.authorizeRequests().antMatchers("/uri/**").hasAuthority("SOME_ROLE");