Skip to content

Instantly share code, notes, and snippets.

@mrioan
Created March 6, 2015 17:23
Show Gist options
  • Save mrioan/c33943292002bcd4cb61 to your computer and use it in GitHub Desktop.
Save mrioan/c33943292002bcd4cb61 to your computer and use it in GitHub Desktop.
JWT creation and verification
/**
* Sample method to obtain data from the JWT response sent by the IDSite and create a new custom JWT
*/
private String createJWT(HttpServletRequest request, String issuer, long ttl) {
IdSiteCallbackHandler idSiteCallbackHandler = application.newIdSiteCallbackHandler(request);
AccountResult accountResult = idSiteCallbackHandler.getAccountResult();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SignatureAlgorithm alg = SignatureAlgorithm.HS256;
String id = UUID.randomUUID().toString();
String sub = accountResult.getAccount().getHref();
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
Key signingKey = new SecretKeySpec(apiKeySecretBytes, alg.getJcaName());
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(now)
.setSubject(sub)
.setIssuer(issuer)
.signWith(alg, signingKey);
if (ttl >= 0) {
long ttlMillis = ttl * 1000;
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
/**
* Sample method to validate and read data from the JWT
*/
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret())).parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}
@trongkhanh
Copy link

apiKey.getSecret() in byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret()); i don't see "api" variable, can you support me for this error?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment