Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 8, 2018 08:58
Show Gist options
  • Select an option

  • Save slmanju/fd29af6f119421f771028ab7f87f831b to your computer and use it in GitHub Desktop.

Select an option

Save slmanju/fd29af6f119421f771028ab7f87f831b to your computer and use it in GitHub Desktop.
public final class JwtUtils {
private static String SECRET = "winteriscoming";
private static int EXPIRATION = 60 * 60 * 1000; // 1 hour
public static String generateToken(final JwtDto jwtDto) {
Claims claims = Jwts.claims().setSubject(jwtDto.getUsername());
claims.put("userId", jwtDto.getUserId() + "");
claims.put("role", jwtDto.getRole());
Date createdDate = new Date();
Date expiration = new Date(createdDate.getTime() + EXPIRATION);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdDate)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
public static JwtDto parseToken(final String token) {
Claims body = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
return JwtDto.builder()
.username(body.getSubject())
.userId(Long.valueOf((String) body.get("userId")))
.role((String) body.get("role"))
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment