Last active
March 2, 2018 16:11
-
-
Save dvas0004/49e26b0a43adbe4aaef7f05c2385c594 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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