首页 > 解决方案 > Spring Security 5 - 为 JWT 和 OpaqueTokens 设置 AuthenticationManagerResolver 失败

问题描述

我正在尝试使用 Spring Security 5.5.1 应用 Spring Documentation 来设置 OAuth 2.0 资源服务器:https ://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2reourceserver-opaqueandjwt

我的配置类类似于 Spring 记录的内容

@Configuration
public class TokenSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorize -> authorize.anyRequest().authenticated()).oauth2ResourceServer(
                oauth2 -> oauth2.authenticationManagerResolver(tokenAuthenticationManagerResolver()));
    }
    
    @Bean
    AuthenticationManagerResolver<HttpServletRequest> tokenAuthenticationManagerResolver() {
        BearerTokenResolver bearerToken = new DefaultBearerTokenResolver();
        JwtAuthenticationProvider jwt = jwt();
        OpaqueTokenAuthenticationProvider opaqueToken = opaqueToken();

        return request -> {
            if (useJwt(request)) {
                return jwt::authenticate;
            } else {
                return opaqueToken::authenticate;
            }
        };
    }
    

    Boolean useJwt(HttpServletRequest request) {
        String token = request.getHeader("Authorization").replaceFirst("Bearer ", "");
        if (JwtChecker.isJwt(token)) {
            return true;
        }
        return false;
    }

}

我还包含一个 application.yml ,格式如下:


server: 
  port: 8082
  servlet: 
    context-path: /resource-server

spring:
  security:
    oauth2:
      resourceserver:
        opaquetoken:
            introspection-uri: https://idp.example.com/introspect
            client-id: introspect-sample
            client-secret: p@ssword
        jwt:
          issuer-uri: https://idp.example.com
          jwk-set-uri: https://idp.example.com/connect/jwks_uri

据我了解,只要我将这些配置放在 application.yml 中,jwt() 和 opaqueToken() Bean 就应该可用,但应用程序仍然无法运行/编译说:

cannot find symbol
[ERROR]   symbol:   method opaqueToken()
[ERROR]   location: class x.x.x.config.TokenSecurityConfig

cannot find symbol
[ERROR]   symbol:   method jwt()
[ERROR]   location: class x.x.x.config.TokenSecurityConfig

以下帖子似乎表明它应该可以工作:https ://github.com/spring-projects/spring-boot/issues/19426

我真的不明白出了什么问题,也许 Spring Docs 错了?当我尝试在没有任何 AuthenticationManagerResolver 的情况下仅设置 JWT 或 Opaque Auth 时,应用程序会编译

我可能正在混合一切......</p>

我还看到了这个示例,它使用了不同的语法(不使用 DSL 来获取 jwt 和 opaqueToken bean:https ://github.com/spring-projects/spring-security/commit/9895d01257679d7cb0d20750ad6d97c53d12fde8 )

标签: javaspring-bootspring-securityjwtspring-security-oauth2

解决方案


推荐阅读