1、使用示例
maven:
<!--jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
封装成工具类:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: Phil
* @Description:
* @Date:Create in 16:00 2019/12/20
* @Modified By:
*/
public class JwtUtil {
/**
* token存活时间,15分钟
*/
private static final long EXPIRE_TIME = 15 * 60 * 1000;
//private static final long EXPIRE_TIME = 15 * 60 * 1000 * 4 * 24 * 365 * 100;
private static final String SECRET = "zengjunyu123456";
private static final String USERNAME = "userName";
private static final String USERID = "userId";
/**
* 从数据声明生成令牌
* @param userName 数据声明
* @param userId 数据声明
* @return 令牌
*/
public static String generateToken(String userName, Long userId) {
Map<String, Object> claims = new HashMap<>(1);
claims.put(USERNAME, userName);
claims.put(USERID, userId);
Date expirationDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SECRET).compact();
}
/**
* 验证令牌
* @param token
* @return
*/
public static Boolean validateToken(String token) {
Claims claims = getClaimsFromToken(token);
if(claims!=null){
return claims.getExpiration().compareTo(new Date())>=0;
}
return false;
}
/**
* @Author: Phil
* @Description: 从令牌中获取用户名
* @Date: 14:36 2019/12/21
*
* @param token
* @return:
*/
public static String getUserNameFromToken(String token){
Claims claims = getClaimsFromToken(token);
if(claims!=null){
return claims.get(USERNAME).toString();
}
return null;
}
/**
* @Author: Phil
* @Description: 从令牌中获取用户id
* @Date: 14:36 2019/12/21
*
* @param token
* @return:
*/
public static Long getUserIdFromToken(String token){
Claims claims = getClaimsFromToken(token);
if(claims!=null){
return Long.valueOf(claims.get(USERID).toString());
}
return -1l;
}
/**
* 从令牌中获取数据声明
* @param token 令牌
* @return 数据声明
*/
private static Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}
public static void main(String[] args) {
String token = generateToken("zengjunyu", 1l);
boolean flag = validateToken(token);
String userName = getUserNameFromToken(token);
}
}