1

I am writing a function that generated JWT Token. I am using JJWT Library and i have imported all necessary files and libraries.

Format : 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();

When i tried running the script it gives

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

I have a private Key and Aud, Iss, Sub,exp. I want to generate JWT token with this in RS256 Format.

Any Suggestions would be helpful.

Raahul
  • 399
  • 1
  • 3
  • 11
  • 1
    Have you checked if the class JacksonSerializer exists inside the loaded jar? – Seba López Sep 01 '20 at 13:05
  • I have copied JacksonSerializer jar to the folder and i have RSA Private Key, But this code has ES256, When i change private key it gives error in keyFactory.generatePrivate(keySpec); – Raahul Sep 01 '20 at 13:50

0 Answers0