Search code examples
javaspring-security

In spring security, use basic-auth per Request Method


Lets say i have this web security config and the url for posting and getting all customers is the same:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .requestMatchers("/customers/**")
            .hasRole("ADMIN")
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
        return http.build();
    }
}

Is there any way i can add security to POST requests to customers only, while allowing GET?


Solution

  • You can specify the matcher:

    @Configuration
    public class SecurityConfiguration {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .requestMatchers(HttpMethod.POST, "/customers/**")
                .hasRole("ADMIN")
    
                .requestMatchers(HttpMethod.GET, "/customers/**")
                .permitAll()
    
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
            return http.build();
        }
    }