Spring REST security - Secure different URLs differently

前端 未结 1 847
野趣味
野趣味 2020-12-05 01:31

I have working REST API under Spring 4 using Basic authentication. These REST services are under /api/v1/** URL. However, I want to add another set of REST endpoints under d

相关标签:
1条回答
  • 2020-12-05 01:52

    Here's a code sample in Java config that uses UserDetailsService and has different security configurations for different URL endpoints:

    @Configuration
    @EnableWebMvcSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        UserDetailsService userDetailsService;
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }
    
        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                        .antMatcher("/api/v1/**")
                        .httpBasic()
                            .realmName("API")
                            .and()
                        .csrf().disable()
                        .authorizeRequests()
                        .antMatchers("/api/v1/**").authenticated();
            }
        }
    
        @Configuration
        @Order(2)
        public static class ApiTokenSecurityConfig extends WebSecurityConfigurerAdapter{
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                        .antMatcher("/api/v2/**")
                        /* other config options go here... */
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题