0

我正在编写一个生成 JWT 令牌的函数。我正在使用 JJWT 库,并且我已经导入了所有必要的文件和库。

格式:RS256

import io.jsonwebtoken.*

import java.security.PrivateKey
import java.util.Base64
import java.util.Base64.Decoder

import java.nio.charset.StandardCharsets

import java.security.interfaces.ECPrivateKey
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.spec.PKCS8EncodedKeySpec

//20 minutes from now
def expiry_time = (System.currentTimeMillis() / 1000 + 1200)
def exp = Math.round(expiry_time)

log.info "Exp Time : " + exp

//JWT Payload (update with your Issuer ID)
String jsonString = """{"aud":["https://sample.com"],
"iss":"usage@test.com",
"sub":"usage@test.com",
"exp":${exp}}""";

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256
 
log.info "JSON    : " + jsonString

def base64EncodedPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg74+aaeYnqEIewDn8Xh0rQXaQqAHSLGDyL9fV0p1hhxGgCgYIKoZIzj0DAQehRANCHOTEUjCMi4Vt7JGZjsRP1zF765oerCqfvHZYGqSeJl8AmK0awchcqAaMlw7hROoA2MToqx+llo2p9lZCQYbeerau"

ECPrivateKey signingKey
Base64.Decoder dec= Base64.getDecoder();
keyBytes = dec.decode(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII));

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RS256");
signingKey = keyFactory.generatePrivate(keySpec);

// Actual Call
String jwtToken = Jwts.builder()
    // Header
    .setHeaderParam("typ","JWT")
    .setHeaderParam("alg","RS256")
    // Payload
    .setPayload(jsonString)
    .signWith(SignatureAlgorithm.ES256, signingKey)
    .compact();

当我尝试运行它给出的脚本时

io.jsonwebtoken.lang.UnknownClassException: Unable to load class named [io.jsonwebtoken.io.JacksonSerializer] from the thread context, current, or system/application ClassLoaders. All heuristics have been exhausted. Class could not be found. error at line: 41

我有一个私钥和 Aud、Iss、Sub、exp。我想用这个以 RS256 格式生成 JWT 令牌。

任何的意见都将会有帮助。

4

0 回答 0