Spring REST安全性-以不同方式保护不同的URL


问题内容

我在Spring 4下使用基本身份验证使用了REST API。这些REST服务位于/ api / v1 / URL下。但是,我想在不同的URL /
api / v2 /
下添加另一组REST端点,但是受基于令牌的身份验证保护。

是否可以使用一个servlet做到这一点?如何配置Spring Security以对不同的URL使用不同形式的身份验证?

谢谢。


问题答案:

这是Java配置中的代码示例,该示例UserDetailsService针对不同的URL端点使用并具有不同的安全性配置:

@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... */
        }

    }
}