Search code examples
javaspringspring-bootspring-securitykeycloak

Spring Security 6 .permitAll() not working


I'm bulding an API using Java 21, Spring boot 3 and spring security 6 authenticating in keycloak 22.

I have this code that configure my spring security:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    CsrfTokenRequestAttributeHandler csrfRequestHandler = new CsrfTokenRequestAttributeHandler();
    csrfRequestHandler.setCsrfRequestAttributeName("_csrf");

    return http
            .cors(Customizer.withDefaults())
            .csrf(csrf -> csrf
                    .csrfTokenRequestHandler(csrfRequestHandler)
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
            .authorizeHttpRequests(requests -> requests
                    .requestMatchers("auth/**").permitAll()
                    .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(jwt -> jwt
                            .jwtAuthenticationConverter(grantedAuthoritiesExtractor())))

            .build();
}

I also have this configuration pointing to my Keycloak to validate the token. security: oauth2: resourceserver: jwt: issuer-uri: 'http://localhost:8080/realms/core-creare'

I'm trying to bypass authentication in the path "/auth", but the .permitAll() its not working. When I do a post request in "/auth", return as 401 unauthorized.


Solution

  • I solved the problem! In my security filter chain I needed to ignore the /auth in CSRF config:

    return http
           .cors(Customizer.withDefaults())
           .csrf(csrf -> csrf
                .csrfTokenRequestHandler(csrfRequestHandler)
                .ignoringRequestMatchers("/auth/**")
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
           .authorizeHttpRequests(requests -> requests
                .requestMatchers(new AntPathRequestMatcher("/auth/**")).permitAll()
                .anyRequest().authenticated())
           .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(grantedAuthoritiesExtractor())))
           .build();