如何在Spring中配置无Issuer-uri的OAuth2对接Jobber
解决方案
问题根源在于你的SecurityFilterChain中配置了oauth2ResourceServer().jwt(),这要求Spring容器必须存在JwtDecoder类型的Bean,但你移除了原有的基于issuer-uri的实现,导致容器找不到该Bean抛出异常。以下是适配Jobber的修改步骤:
1. 补充Jobber的JWKS端点配置
首先在application.yml的OAuth2 provider配置中添加Jobber的JWKS(JSON Web Key Set)地址,用于获取验证JWT的公钥:
security: oauth2: client: provider: oidc: authorization-uri: https://api.getjobber.com/api/oauth/authorize token-uri: https://api.getjobber.com/api/oauth/token jwk-set-uri: https://api.getjobber.com/.well-known/jwks.json # 确认Jobber官方文档中的JWKS地址 registration: oidc: client-id: xxx client-secret: xxx authorization-grant-type: authorization_code scope: clients, invoices, users, offline_access redirect-uri: http://localhost:9000/login/oauth2/code/oidc
2. 重新创建JwtDecoder Bean
无需依赖issuer-uri,直接基于JWKS URI构建JwtDecoder,并按需添加验证规则(比如audience校验):
@Bean JwtDecoder jwtDecoder(JHipsterProperties jHipsterProperties) { // 基于Jobber的JWKS地址创建解码器 NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri("https://api.getjobber.com/.well-known/jwks.json").build(); // 保留原有的audience验证逻辑(如果需要) OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(jHipsterProperties.getSecurity().getOauth2().getAudience()); OAuth2TokenValidator<Jwt> defaultValidators = JwtValidators.createDefault(); OAuth2TokenValidator<Jwt> combinedValidators = new DelegatingOAuth2TokenValidator<>(defaultValidators, audienceValidator); jwtDecoder.setJwtValidator(combinedValidators); // 如果需要自定义Claim转换,继续添加原有的CustomClaimConverter // jwtDecoder.setClaimSetConverter(new CustomClaimConverter(...)); return jwtDecoder; }
3. 确认SecurityFilterChain配置
确保你的security链配置无需调整,保持现有结构即可:
.and() .oauth2Login(oauth2LoginCustomizer()) .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(authenticationConverter()) .and() .and() .oauth2Client();
特殊情况处理
如果Jobber未公开JWKS端点,你需要手动获取其公钥并直接配置:
@Bean JwtDecoder jwtDecoder(JHipsterProperties jHipsterProperties) throws Exception { // 替换为Jobber提供的公钥内容 String publicKeyContent = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...\n-----END PUBLIC KEY-----"; // 解析公钥 RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec( Base64.getDecoder().decode( publicKeyContent.replaceAll("\\n", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") ) )); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(publicKey).build(); // 添加验证规则(同步骤2) OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(jHipsterProperties.getSecurity().getOauth2().getAudience()); OAuth2TokenValidator<Jwt> combinedValidators = new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefault(), audienceValidator); jwtDecoder.setJwtValidator(combinedValidators); return jwtDecoder; }
内容的提问来源于stack exchange,提问作者elk-tamer
相关产品推荐
相关产品推荐

