I'm trying to implement a controller authentication using Spring Boot security.
When customizing my filterChain
I get 401 Unauthorized for resources I have specifically permitted.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/test/**").permitAll()
.requestMatchers(h2ConsolePath + "/**").permitAll()
.anyRequest().authenticated();
http
.headers()
.frameOptions().sameOrigin();
http
.authenticationProvider(authenticationProvider());
http
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
For example I want to access my h2-console and I don't want any authentication to happen when I access the h2-console. But I still get an error message with the status code 403 Forbidden.
Even when I remove this line .anyRequest().authenticated();
I get the same error, which makes me think that this whole filter chain doesn't get applied maybe? But when I debug it and set a breakpoint inside the method the program jumps inside the method, so it should get applied?
After many hours of research I'm not sure how to proceed.
Edit:
I also added a TestController
with a TestResource
and without the @PreAuthorize
annotation and when I test it in Postman I get this error message:
Full authentication is required to access this resource
As already mention I have the feeling that the filter chain isn't applied because even when I remove .anyRequest().authenticated
the same error still occures, so it doesn't really make sense to me.
I finally found the solution. I went back to Java version 1.8 and used antMatchers
instead of requestMatchers
.
So this is my final code:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.antMatchers(h2ConsolePath + "/**").permitAll()
.anyRequest().authenticated();
http
.headers()
.frameOptions().sameOrigin();
http
.authenticationProvider(authenticationProvider());
http
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}