Create and Sign a JSON Web Token (JWT) with Java
import java.io.FileReader; import java.io.IOException; import java.security.PrivateKey; import java.util.Date; import java.util.UUID; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; public class SignToken { public static void main(String[] args) { PEMParser reader = null; try { // Reading a PEM encoded private key reader = new PEMParser( new FileReader("PRIVATE_KEY_PEM_FILE_PATH")); PEMKeyPair keys = (PEMKeyPair) reader.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PrivateKey privateKeyJava = converter.getPrivateKey(keys.getPrivateKeyInfo()); JwsHeaders header = new JwsHeaders(SignatureAlgorithm.RS256); JwtClaims body = new JwtClaims(); Date now = new Date(); body.setAudience("https://AAAS_PLATFORM/idp/YOUR_TENANT/authn/token"); body.setExpiryTime(now.getTime() + 60 * 60 * 1000); body.setIssuer("YOUR_CLIENTID"); body.setTokenId(UUID.randomUUID().toString()); body.setSubject("YOUR_CLIENTID"); body.setNotBefore(now.getTime() - 30); body.setIssuedAt(now.getTime()); JwsJwtCompactProducer producer = new JwsJwtCompactProducer(header, body); // Prints the token ready to be sent to the Authentication Service ! System.out.println(producer.signWith(privateKeyJava)); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } }