看链接:http://www.jianshu.com/p/576dbf44b2ae
来个工具类:
import java.io.Serializable; import java.util.Date; import java.util.Map; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JwtTokenService implements Serializable { private static final long serialVersionUID = -3301605591108950415L; private static final String CLAIM_KEY_CREATED = "created"; private String secret="absd"; private Long expiration=7200L; /** * 获取创建token时间 * @param token * @return */ public Date getCreatedDateFromToken(String token) { Date created; try { final Claims claims = getClaimsFromToken(token); created = new Date((Long) claims.get(CLAIM_KEY_CREATED)); } catch (Exception e) { created = null; } return created; } /** * 获取过期时间 * @param token * @return */ public Date getExpirationDateFromToken(String token) { Date expiration; try { final Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; } /** * 判断是否过期 * @param token * @return */ private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } /** * 获取jwt中的body部分 * @param token * @return */ public Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; // throw e; } return claims; } public String getSubject(String token){ try { return getClaimsFromToken(token).getSubject(); }catch (Exception e){ } return null; } /** * 生成过期时间 * @return */ private Date generateExpirationDate() { return new Date(System.currentTimeMillis() + expiration * 1000); } /** * 生成token * @param claims * @return */ public String generateToken(Map<String, Object> claims, String subject) { return Jwts.builder() .setClaims(claims) .setSubject(subject) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String generateToken( String subject) { return Jwts.builder() .setSubject(subject) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String refreshToken(String token) { String refreshedToken; try { final Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims,claims.getSubject()); } catch (Exception e) { refreshedToken = null; } return refreshedToken; } /** * token是否过期 * @param token * @return */ public Boolean validateToken(String token) { Claims claims = getClaimsFromToken(token); if(claims==null) return false; return !isTokenExpired(token); } }