Skip to content

Instantly share code, notes, and snippets.

@gjyoung1974
Created October 24, 2017 04:34
Show Gist options
  • Save gjyoung1974/f3eeb676a2ef6aac8b70a73461facb9f to your computer and use it in GitHub Desktop.
Save gjyoung1974/f3eeb676a2ef6aac8b70a73461facb9f to your computer and use it in GitHub Desktop.
package com.gyoung.auto.jwt.demo;
import java.io.IOException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import org.bouncycastle.util.encoders.Base64;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureGenerationException;
public class JTWSigner {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws NoSuchAlgorithmException, SignatureGenerationException, IOException {
Date date = new Date();
Date expiryDate = new Date();
expiryDate.setDate(date.getDate() + 100);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
RSAPublicKey publicKey = (RSAPublicKey) keyGen.genKeyPair().getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyGen.genKeyPair().getPrivate();
String privKey = Base64.toBase64String(privateKey.getEncoded());
String pubKey = Base64.toBase64String(publicKey.getEncoded());
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
String[] permsissions = { "do", "stuff", "with", "otherstuff" };
String token = JWT.create()
.withIssuedAt(date)
.withNotBefore(date)
.withExpiresAt(expiryDate)
.withIssuer("Gordon Young")
.withSubject("Gordon Young")
.withArrayClaim("permissions", permsissions)
.withAudience("All the peeps in the word")
.withClaim("ClaimName", "ClaimValue")
.sign(algorithm);
System.out.println("Private key");
System.out.println(privKey + "\n\n");
System.out.println("Public key");
System.out.println(pubKey + "\n\n");
System.out.println("token");
System.out.println(token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment