Search code examples
spring-bootsecurityspring-security

Spring security returns 401 instead of 403


I am using spring boot 3 and spring security 6. I have configured the following security chain

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests(requests -> {requests
                .requestMatchers("/", "/login").permitAll(); //these urls don't require authentication
                //.anyRequest().permitAll(); //all other requests are authenticated
                requests.requestMatchers(HttpMethod.POST).hasRole("ADMIN");
                requests.requestMatchers(HttpMethod.GET).hasAnyRole("USER", "ADMIN");
                    requests.anyRequest().authenticated();
                })
                
                .httpBasic(Customizer.withDefaults()) //enable basic authentication, used for APIs
                .formLogin(form -> form  //enable form based authentication, for UI
                        .loginPage("/login")
                        .permitAll());

        return http.build();
}

Rules configured for GET method are working fine but when I use POST method things are not working as expected.

On using POST method, I am getting 401 unauthorized error for both USER and ADMIN roles, rather In was expecting 403 error for user with role USER and access being allowed to user with role ADMIN.

Is there something wrong with my configuration?


Solution

  • I figured out the problem. I has to disable the csrf for POST method to work.

    This is how you can do it in spring boot 3 / spring security 6

    .csrf(csrf -> csrf.disable())
    

    Hope this helps.