Kotlin 中的 Spring,使用 base64url 编码的 JWT Token

问题描述 投票:0回答:1

我正在尝试使用

NimbusJwtEncoder
创建 JWT 令牌,并且我正在正确获取令牌。但每次我在
jwt.io
上验证它时,它都说签名无效,因为它没有在 base64url 上正确编码。

喜欢这个最后的测试令牌

"eyJraWQiOiJabVZrWWpBMk56TXRaR1V6WmkwMFpEVXlMVGt5TUdNdE5qUmlabUpoWmpVeU5HWTQiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzZWxmIiwic3ViIjoiU2FoZXIgQWxTb3VzIiwiZXhwIjoxNjc5OTQ1MTIxLCJpYXQiOjE2Nzk5Mzk3MjEsInNjb3BlIjoiUk9MRV9VU0VSIn0.tLTsk03Rg7ZjY3yjyM_lGveeT0KRCPJBSBlpcOzXA3n4pGA5TjHSD3GdVL3tGhH1kyhLt2Xqk2Mwa88w6fWeBvrBa3V8M8GVcZKusXS52XxDlBSag6ouQKsqQBk3HRDfORHw_U5SwV2Yuu_gFlghDjv2A9wNv8lTQSKSEwS4vsm7UOZQX9ERMdWTbKaW4-CTAiHazGsmRViiWpiYKkp4p0EZez_p0vSaQ_nFhQ_uuU9W_7HjkJgC4kD9mMhrdyhOpXllwkZkxP5VIkuRKKa4_uooUSP_taTloSZiYITz-CTgFsqekmHZhVj72bFDINBzO3pzbavjagwT1vJcw4reEA"

我改变了几种生成密钥的方法,包括 Base64 编码器,但结果相同。

我错过了什么吗?

Security Configuration

 @Bean
    fun jwkSource(): JWKSource<SecurityContext> {
        val jwkSet = JWKSet(rsaKey())
        return JWKSource { jwkSelector: JWKSelector, _: SecurityContext? ->
            jwkSelector.select(
                jwkSet
            )
        }
    }

    @Bean
    fun jwtEncoder(jwkSource: JWKSource<SecurityContext>): JwtEncoder {
        return NimbusJwtEncoder(jwkSource)
    }

    @Bean
    fun jwtDecoder(): JwtDecoder {
        return NimbusJwtDecoder
            .withPublicKey(rsaKey().toRSAPublicKey())
            .build()
    }

    @Bean
    fun rsaKey(): RSAKey {
        val keyPair = keyPair()
        return RSAKey.Builder(keyPair.public as RSAPublicKey)
            .privateKey(keyPair.private as RSAPrivateKey)
            .keyID(UUID.randomUUID().toString())
            .build()
    }

    @Bean
    fun keyPair(): KeyPair {
        return try {
            val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
            keyPairGenerator.initialize(2048)
            keyPairGenerator.generateKeyPair()
        } catch (e: Exception) {
            throw IllegalStateException(
                "Unable to generate an RSA Key Pair", e
            )
        }
    }
class JwtTokenService(private val jwtEncoder: JwtEncoder) {
    fun generateToken(authentication: Authentication): String {
        val scope = authentication
            .authorities
            .joinToString(" ") {obj: GrantedAuthority ->
                obj.authority
            }

        val claims = JwtClaimsSet.builder()
            .issuer("self")
            .issuedAt(Instant.now())
            .expiresAt(Instant.now().plus(90, ChronoUnit.MINUTES))
            .subject(authentication.name)
            .claim("scope", scope)
            .build()

        return jwtEncoder
            .encode(JwtEncoderParameters.from(claims))
            .tokenValue
    }
}

我不断收到这 2 个警告...顺便说一下,当您将鼠标移到令牌黄色区域时,警告会消失...

spring-boot kotlin jwt spring-security-oauth2
1个回答
0
投票

好吧,我想把这个留在这里…… 这是使用

NimbusJwtEncoder
.

在 kotlin 中使用 Spring 创建 JWT 的正确方法

我希望有人会使用它。

问候

© www.soinside.com 2019 - 2024. All rights reserved.