【问题标题】:Spring Security with OAuth2 and anonymous access具有 OAuth2 和匿名访问的 Spring Security
【发布时间】:2018-12-08 12:01:00
【问题描述】:

我的 Spring REST API 使用 Spring Security 和 OAuth2 进行保护,我可以成功检索令牌并访问我的 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 身份验证成为可选?

【问题讨论】:

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


    【解决方案1】:

    我放弃了我的@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 现在可以在有或没有身份验证的情况下调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 2015-10-09
      • 2012-08-18
      • 2018-08-08
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多