无法在同一项目中使用ResourceServerConfigurerAdapter和WebSecurityConfigurerAdapter

时间:2017-10-21 11:36:45

标签: spring spring-boot spring-security

我有一个项目,提供使用表单登录的网页。现在我希望该项目还公开一个使用oauth的api。我们的想法是使用requestMatchers设置ResourceServerConfigurerAdapter和WebSecurityConfigurerAdapter,以使用不重叠的不同路径。但是,我要么 OAuth2AuthenticationProcessingFilter 是UsernamePasswordAuthenticationFilter,而不是两者。

ResourceServerConfigurerAdapter:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .requestMatchers()
        .mvcMatchers("/api/**")
        ...
}

如果我的WebSecurityConfigurerAdapter 使用任何requestMatchers,我会得到一个UsernamePasswordAuthenticationFilter但没有OAuth2AuthenticationProcessingFilter。

http
    .authorizeRequests()
    ...

另一方面,如果我在WebSecurityConfigurerAdapter中使用任何请求匹配器,无论具体如何,我都会获得OAuth2AuthenticationProcessingFilter但没有UsernamePasswordAuthenticationFilter。

http
    .requestMatchers()
    .mvcMatchers("/anything")
    .authorizeRequests()
    ...

解决方案?

或者我应该以不同的方式解决这个问题?例如,为api创建一个新项目? (即使这意味着要复制某些代码,例如域对象)

1 个答案:

答案 0 :(得分:1)

考虑使用@Order(40)注释ResourceServerConfigurerAdapter并按以下方式实现configure(HttpSecurity http):

 http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();

@Order(50)注释WebSecurityConfigurerAdapter。在弹簧靴1.5.7上进行了测试。

尝试以最高顺序保护安全配置中的所有可能路径。

Spring为ResourceServerConfigurerAdapter中的安全性配置创建了一个安全过滤器链,为WebSecurityConfigurerAdapter中的安全性配置创建了一个安全过滤器链