@ EnableOAuth2Sso - 如何保护/取消保护资源?

Ken*_*ger 5 spring spring-security spring-boot spring-security-oauth2 spring-cloud

我正在尝试在Spring Cloud Security中使用@ EnableOAuth2Sso功能.具体来说,我试图用OAuth2保护一些资源,同时让其他资源公开访问.我已经设法让这个工作,但我正在查看生成的代码,并想知道是否有一个更清洁的方式.

我在这里关注文档:https: //github.com/spring-cloud/spring-cloud-security/blob/master/src/main/asciidoc/spring-cloud-security.adoc和Spring Boot的类似指导参考.我有一个很小的代码示例,说明了我的困境:https: //github.com/kennyk65/oAuthSsoExample.

简而言之,我希望localhost:8080 /不受保护的资源是公开可用的,我希望localhost:8080/protected资源需要OAuth2(通过github,如配置的那样).我能够使基本的OAuth2行为正常工作,但导致/不受保护的公开可用是有问题的.

首先,文档表明您可以使用OAuth2SsoConfigurer的match()方法来指定要保护的资源.我发现这不起作用; 当我尝试时,我得到一个IllegalStateException,说至少需要一个映射.这似乎是指未实现的configure(HttpSecurity)方法.

接下来,我尝试在configure(HttpSecurity)中指定一个映射,指出"不受保护的"资源应该是不受保护的.但是,这会导致将Http基本安全性应用于该资源.奇怪的是,这导致"受保护"资源完全公开!

// This results in “unprotected” being protected by HTTP Basic
// and “protected” being completely open!   
@Configuration
protected static class OauthConfig extends OAuth2SsoConfigurerAdapter {
  @Override
  public void match(RequestMatchers matchers) {
    matchers.antMatchers("/protected/**");
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/unprotected/**").permitAll();        
  }
}
Run Code Online (Sandbox Code Playgroud)

我一时兴起,故意添加受保护资源的身份验证.这导致受保护的资源获得OAuth2保护(欢呼!)但是未受保护的资源应用了http基本安全性(呵呵?).

// This results in “protected” being protected by OAuth 2
// and “unprotected” being protected by HTTP Basic, even though we say permitAll(): 
@Configuration
protected static class OauthConfig extends OAuth2SsoConfigurerAdapter {
  @Override
  public void match(RequestMatchers matchers) {
    matchers.antMatchers("/protected/**");
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/protected/**”).authenticated();      
        .antMatchers("/unprotected/**").permitAll();        
  }
}
Run Code Online (Sandbox Code Playgroud)

在最后尝试找到魔法组合时,我尝试使用security.basic.enabled:false简单地关闭HTTP基本身份验证.这工作(欢呼!),虽然我仍然有点困惑的问题是映射的问题.

所以我想我的问题是,这是正确的吗?使用OAuth 2保护某些资源并让其他人独处的最佳方法是什么?

Dav*_*yer 2

如果匹配,/protected/**则添加访问规则是没有意义的/unprotected/**(路径不匹配,因此永远不会应用该规则)。您要么需要另一个过滤器链来处理“未受保护”的资源,要么需要为 SSO 提供更广泛的匹配。在前一种情况下,如果您不介意关闭 Spring Security 提供的安全性,则可以使用从 Spring Security 获得的默认安全性。例如

\n\n
@Configuration\nprotected static class OauthConfig extends OAuth2SsoConfigurerAdapter {\n  @Override\n  public void match(RequestMatchers matchers) {\n    matchers.antMatchers("/protected/**");\n  }\n  @Override\n  public void configure(HttpSecurity http) throws Exception {\n    http\n      .authorizeRequests()\n        .antMatchers("/**\xe2\x80\x9d).authenticated();      \n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

并设置security.basic.enabled=false.

\n