具有OAuth2和匿名访问权限的Spring Security

时间:2018-06-29 10:03:12

标签: spring spring-security oauth-2.0 spring-security-oauth2

我有受Spring Security和OAuth2保护的Spring REST API,我可以成功检索令牌并访问我的API。我的应用程序自行定义了OAuth2客户端。

现在,我希望用户可以对某些资源进行匿名访问。用例非常简单:我希望我的应用程序无需登录即可使用-但是如果他们登录了,我希望可以访问该主体

到目前为止,这是我的WebSecurityConfigurerAdapter

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/api1").anonymous().and()
            .authorizeRequests().antMatchers("/ap2**").permitAll();
}

一旦我添加了第二个antMatcher / anonymous,它就无法工作,并且也不能真正表达我的意图-例如我不会对api1 GET进行匿名访问,但会在POST上进行身份验证(使用@PreAuthorize很容易)。

如何使OAuth2身份验证为可选?

1 个答案:

答案 0 :(得分:0)

我放下@EnableWebSecurity并使用ResourceServerConfigurerAdapter,如下所示:

@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/api/api1", "/api/api2").permitAll()
                .and().authorizeRequests()
                    .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("my-resource-id");
    }
}

/api/api1现在可以通过或不通过身份验证来调用。

相关问题