我正在尝试基于 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方法。
//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}\nRun 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 = …Run Code Online (Sandbox Code Playgroud)