Skip to content

Instantly share code, notes, and snippets.

@dvas0004
Last active March 2, 2018 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvas0004/49e26b0a43adbe4aaef7f05c2385c594 to your computer and use it in GitHub Desktop.
Save dvas0004/49e26b0a43adbe4aaef7f05c2385c594 to your computer and use it in GitHub Desktop.
@Service
public class TokenCreator {
@Value("${jwtSecret}")
private String jwtSecret;
private Algorithm algorithm = null;
public TokenCreator() { }
public String issueToken(String[] claims, String subject, Date expiryDate){
try {
this.algorithm = Algorithm.HMAC256(jwtSecret);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* If no expiry date given, default to a 24hour expiry time
*/
if (expiryDate == null){
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Use today's date.
c.add(Calendar.HOUR_OF_DAY, 24); // Adds 24 hours
expiryDate = c.getTime();
}
Builder tokenBuilder = JWT.create()
.withIssuer("YOUR ORGANIZATION HERE")
.withSubject(subject)
.withExpiresAt(expiryDate);
/*
* Cycle through the claims and add them to our JWT
*/
for (String claim : claims){
tokenBuilder.withClaim(claim, true);
}
/*
* Sign and issue the JWT
*/
String issuedToken = tokenBuilder.sign(algorithm);
return issuedToken;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment