【问题标题】:Spring Security + OAuth, fallback if access token absentSpring Security + OAuth,如果没有访问令牌则回退
【发布时间】:2015-03-30 10:39:04
【问题描述】:

我在我的应用程序中使用 Spring Security 来保护我的大部分端点。我正在使用 Spring Security OAuth2 来保护某个子集。 外部服务器和资源服务器本身的用户都可以访问此 OAuth 保护端点子集。

是否可以在此端点上同时使用两种保护,并使用非此即彼?如果用户从外部服务器访问端点,他们将需要 OAuth 访问令牌才能进入,如果用户直接登录到资源服务器,他们将没有访问令牌,但我想使用我的其他过滤器链做我的标准身份验证。

我以前从未见过带有两个独立过滤器链的 HTTP 块,但也许有一些我不知道的方法。

【问题讨论】:

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


    【解决方案1】:

    我认为受保护资源不需要 2 个过滤器链,只需要一些考虑到可能遇到的不同身份验证的访问规则。例如,sparklr2 demo 是一个资源服务器,它接受 cookie 以及 /photos 端点上的令牌。在 sparklr 中,您有 1 个过滤器链(WebSecurityConfigurerAdapter)用于登录和授权端点,1 个(ResourceServerConfigurerAdapter)用于受保护的资源。默认情况下,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) 和一个使用令牌或 cookie 的资源 (/photos)。

    【讨论】:

    • Dave 您是否建议将其全部配置在 ResourceServerConfiguration 中而无需单独的 WebSecurityConfigurerAdapter ?而且我在 sparklr2 中找不到为同一个端点配置两个身份验证的部分?我一直对如果不弄乱过滤器就无法实现它很感兴趣,所以如果你能指出我的例子,我会很感激
    • 成功了,为我节省了大量时间和精力。很好的答案,感谢您的帮助!
    • 不,不能让它为我工作。我在 WebSecurityConfigurerAdapter 中指定的任何内容都会被忽略。
    • 也适合我!如果您想使用 Basic Auth 作为后备,请不要忘记将 .and().httpBasic().realmName("MyRealm") 附加到链中。
    猜你喜欢
    • 2015-10-14
    • 2013-07-28
    • 1970-01-01
    • 2016-09-09
    • 2019-10-01
    • 2023-02-03
    • 2019-11-12
    • 2020-02-08
    • 2015-10-14
    相关资源
    最近更新 更多