Skip to content

Instantly share code, notes, and snippets.

@molekilla
Created June 27, 2017 14:00
Show Gist options
  • Save molekilla/31ceb6db34dd5c1cce48d5ce3ba6dad9 to your computer and use it in GitHub Desktop.
Save molekilla/31ceb6db34dd5c1cce48d5ce3ba6dad9 to your computer and use it in GitHub Desktop.
jwt java signing
private String createBearerToken() throws Exception {
byte[] decoded = ("-----BEGIN RSA PRIVATE KEY-----\n" +
"-----END RSA PRIVATE KEY-----\n").getBytes();
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(decoded))));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
java.security.interfaces.RSAPrivateKey generatedPvk = (java.security.interfaces.RSAPrivateKey)kp.getPrivate();
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(generatedPvk);
// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("alice")
.issuer("https://c2id.com")
.expirationTime(new Date(new Date().getTime() + 60 * 1000))
.build();
SignedJWT signedJWT = new SignedJWT(
new JWSHeader(JWSAlgorithm.RS256),
claimsSet);
// Compute the RSA signature
signedJWT.sign(signer);
return signedJWT.serialize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment