更改 Spring oauth2ResourceServer JWT ex。使用单个密钥而不是密钥对会引发异常“无法选择 JWK 签名密钥”

Pla*_*aul 5 rest spring jwt oauth2resourceserver

我正在尝试基于 Spring 新的授权服务器和此示例,使用 JWT-security 实现 Spring Boot Rest 后端:https ://github.com/spring-projects/spring-security-samples/tree/main/servlet /spring-boot/java/jwt/登录

\n

它使用非对称密钥来签名和验证令牌,这似乎有点矫枉过正,因为身份验证(生成令牌的位置)和授权(验证)都发生在同一服务器上。因此,为了简化部署(只需通过环境变量传递单个密钥),我一直在尝试重写它以使用单个共享密钥。\n示例代码实现了两个 Bean 组件,一个用于创建 JwtEncoder(使用RSA 私钥)和 JWTDecoder 的一个(使用匹配的公钥)。\n我已经按照 \xe2\x80\x9cSpring Security in Action\xe2\x80\x9d 书中第 15 章的说明重写了解码器,所以我假设这个应该有效,因为NimbusJwtDecoder提供了一种withSecretKey方法。

\n
//Will eventually come via an environment variable\nstatic byte[] secret = "j8IoV1jF67".getBytes();\n@Bean\nJwtDecoder jwtDecoder() {\n  //      return NimbusJwtDecoder.withPublicKey(this.key).build();\n  SecretKey theKey = new SecretKeySpec(secret, 0, secret.length, "AES");\n  return NimbusJwtDecoder.withSecretKey(theKey).build();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我已经实现了编码器,它正在解决问题,就像这样(注释掉的代码是使用私有 RSA 密钥的原始代码:

\n
@Bean\nJwtEncoder jwtEncoder() {\n  // JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build();\n  // JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));\n  // return new NimbusJwtEncoder(jwks);\n  SecretKey originalKey = new SecretKeySpec(secret, 0, secret.length, "AES");\n  JWKSource<SecurityContext> immutableSecret = new ImmutableSecret<SecurityContext>(originalKey);\n  return new NimbusJwtEncoder(immutableSecret);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

当我登录(通过 POST /token 端点)使用编码器的行时:

\n
return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();\n
Run Code Online (Sandbox Code Playgroud)\n

抛出这个异常

\n
org.springframework.security.oauth2.jwt.JwtEncodingException: An error occurred while attempting to encode the Jwt: Failed to select a JWK signing key\n    at org.springframework.security.oauth2.jwt.NimbusJwtEncoder.selectJwk(NimbusJwtEncoder.java:134)\n    at org.springframework.security.oauth2.jwt.NimbusJwtEncoder.encode(NimbusJwtEncoder.java:108)\n
Run Code Online (Sandbox Code Playgroud)\n

关于如何使用简单的共享密钥而不是非对称密钥来实现此示例,有什么建议吗?

\n