Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@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