我在我的应用程序中使用 Spring Security 来保护我的大部分端点。我正在使用 Spring Security OAuth2 来保护某个子集。 这个受 OAuth 保护的端点子集将被外部服务器和资源服务器本身的用户访问。
是否可以在此端点上同时使用两种保护,并使用非此即彼的方式?如果用户从外部服务器访问端点,他们将需要一个 OAuth 访问 token 才能进入,如果用户直接登录到资源服务器,他们将没有访问 token ,但我想使用我的其他过滤器链进行我的标准身份验证。
我以前从未见过带有两个独立过滤器链的 HTTP block ,但也许有一些我不知道的方法可以做到这一点。
最佳答案
我认为 protected 资源不需要 2 个过滤器链,只需要一些考虑到可能遇到的不同身份验证的访问规则。 sparklr2 demo例如,是一个资源服务器,它在其/photos 端点上接受 cookie 和 token 。在 sparklr 中,您有 1 个过滤器链(WebSecurityConfigurerAdapter
)用于登录和授权端点,1 个(ResourceServerConfigurerAdapter
)用于 protected 资源。默认情况下,ResourceServerConfigurerAdapter
在 WebSecurityConfigurerAdapter
之前应用,因此它必须不匹配登录和授权资源。相关的匹配器和访问规则是这样的:
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/photos/**", "/oauth/users/**", "/oauth/clients/**","/me")
.and()
.authorizeRequests()
.antMatchers("/me").access("#oauth2.hasScope('read')")
.antMatchers("/photos").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
...
}
在这里,您会看到一个仅限 OAuth 的资源 (/me
) 和一个根据访问规则使用 token 或 cookie (/photos
) 的资源。
关于java - Spring Security + OAuth,如果访问 token 不存在则回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244615/