Auth0 provides two JWT libraries, one for Node: node-jsonwebtoken, and one for Java: java-jwt. It turns out that java-jwt does not support public/private key pairs.
However, another java library, the jjwt library, claims to support that feature. However, the documentation does not show how one can use own public/private key pairs in jjwt.
I created the private/public key pair, and used it successfully in Node with node-jsonwebtoken:
var key = fs.readFileSync('private.key');
var pem = fs.readFileSync('public.pem');
var header = {...};
var payload = {...};
header.algorithm = "RS256";
var message = jsonwebtoken.sign(payload, key, header);
var decoded = jsonwebtoken.verify(message, pem, {algorithm: "RS256"});
But I found no way of doing the same in Java with jjwt.
Anyone has a working example of how to use private/public keys for JWT in Java with jjwt?
JWTs in OpenID Connect We have mentioned the use of JWT in OpenID Connect before. The provider issues an identity token to the client. That identity token contains information about the user's authentication with the provider. The identity token is a JWT token, signed with the provider's private key.
The JSON Web Key Set (JWKS) is a set of keys containing the public keys used to verify any JSON Web Token (JWT) issued by the authorization server and signed using the RS256 signing algorithm. When creating applications and APIs in Auth0, two algorithms are supported for signing JWTs: RS256 and HS256.
The jwt token is signed using private key. The auth server provides the public key publicly on a url in the form of JSON Web Key Set(JWKS). During verification the public keys are fetched. Here is an example of JWKS.
Here is what I have followed
Create Keystore
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
You can create Key store from existing private key and public key. Google it how to do it.
Load Keystore
KeyStore ks = KeyStore.getInstance("JKS");
InputStream readStream = // Use file stream to load from file system or class.getResourceAsStream to load from classpath
ks.load(readStream, "password".toCharArray());
Key key = ks.getKey("selfsigned", "password".toCharArray());
readStream.close();
Use JJwt api to sign the message
String s = Jwts.builder().setSubject("Abc").signWith(SignatureAlgorithm.RS512, key).compact();
Use JJwt api to claim the message
X509Certificate certificate = (X509Certificate) keyEntry.getCertificate();
Jwts.parser().setSigningKey(certificate.getPublicKey()).parseClaimsJws(s).getBody().getSubject().equals("Abc");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With