generate jwt private key code example

Example 1: generate private key for jwt

PrivateKey privateKey = // Load an RSA private key from configuration
Instant now = Instant.now();

String jwt = Jwts.builder()
        .setAudience("https://${yourOktaDomain}/oauth2/default/v1/token")
        .setIssuedAt(Date.from(now))
        .setExpiration(Date.from(now.plus(5L, ChronoUnit.MINUTES)))
        .setIssuer(clientId)
        .setSubject(clientId)
        .setId(UUID.randomUUID().toString())
        .signWith(privateKey)
        .compact();

Example 2: generate rs256 key pair

ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key
# Don't add passphrase
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
cat jwtRS256.key
cat jwtRS256.key.pub

Tags:

Misc Example