在同一个请求上同时使用这两种配置是不明确的。可能有一些解决方案,但更清楚地定义单独的请求组:
-
OAuth2Sso:对于来自浏览器的用户,我们希望将他们重定向到令牌的身份验证提供程序
-
ResourceServer:通常用于 api 请求,带有从某处获得的令牌(很可能来自同一个身份验证提供程序)
为此,请使用请求匹配器将配置分开:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Bean("resourceServerRequestMatcher")
public RequestMatcher resources() {
return new AntPathRequestMatcher("/resources/**");
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.requestMatcher(resources()).authorizeRequests()
.anyRequest().authenticated();
}
}
并从 sso 过滤器链中排除这些:
@Configuration
@EnableOAuth2Sso
public class SsoSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("resourceServerRequestMatcher")
private RequestMatcher resources;
@Override
protected void configure(final HttpSecurity http) throws Exception {
RequestMatcher nonResoures = new NegatedRequestMatcher(resources);
http
.requestMatcher(nonResoures).authorizeRequests()
.anyRequest().authenticated();
}
}
并将你所有的资源放在/resources/**下
当然,在这种情况下,两者都将使用相同的 oauth2 配置(accessTokenUri、jwt.key-value 等)
更新1:
实际上您可以通过使用此请求匹配器进行上述配置来实现您的原始目标:
new RequestHeaderRequestMatcher("Authorization")
更新 2:
(@sid-morad 评论的解释)
Spring Security 为每个配置创建一个过滤器链。每个过滤器链的请求匹配器按照配置的顺序进行评估。
WebSecurityConfigurerAdapter 默认排序为 100,ResourceServerConfiguration 默认排序为 3。这意味着首先评估ResourceServerConfiguration 的请求匹配器。对于这些配置,可以覆盖此顺序,例如:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration configuration;
@PostConstruct
public void setSecurityConfigurerOrder() {
configuration.setOrder(3);
}
...
}
@Configuration
@EnableOAuth2Sso
@Order(100)
public class SsoSecurityConfiguration extends WebSecurityConfigurerAdapter {
...
}
所以是的,上面示例中的SsoSecurityConfiguration 不需要请求匹配器。但很高兴知道背后的原因:)