Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - permitAll not working using SecurityFilterChain

I have a Spring Boot application where I need to make certain endpoints accessible to all users without requiring authentication. To achieve this, I am using permitAll().

However, when I try to access one of these endpoints, http://localhost:8080/content/123, a CustomOncePerRequestFilter is being called, which shouldn't happen as it is supposed to be accessible to all users.

The rest of the endpoints are secured and working as expected.

I am seeking guidance on why this is happening and how to fix it. My SecurityConfiguration code is as follows.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Autowired
    private CustomOncePerRequestFilter tokenFilter;

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeHttpRequests()
                .antMatchers("/art/**","/content/**").permitAll()
                .and().authorizeHttpRequests()
                .antMatchers("/api/contenteditor/feed/**").hasAnyRole("SITE_ADMIN", "STANDARD_ADMIN", "DOMAIN_MEMBER")
                .anyRequest().authenticated().and()
                .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        http.cors().configurationSource(source);
        return http.build();
    }

}
like image 835
Harsh Kanakhara Avatar asked Jul 28 '26 09:07

Harsh Kanakhara


1 Answers

Although it may seem strange, the only effective resolution I have found is to override the shouldNotFilter() method within my custom OncePerRequestFilter implementation and include all the paths that require exemption from authentication.

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    return request.getServletPath().startsWith("/art");
}
like image 141
Harsh Kanakhara Avatar answered Jul 30 '26 22:07

Harsh Kanakhara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!