1. pom.xml
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
2. class
/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke
* @Date: 2018/8/29 on 上午10:50
* @description:
*/
public class TestUtils {
/**
* token秘钥,请勿泄露,请勿随便修改 backups:JKKLJOoasdlfj
* 别人篡改数据,但是签名的密匙是在服务器存储,密匙不同,生成的sign也不同。
* 所以根据sign的不同就可以知道是否篡改了数据。
*/
private static final String SECRET = "JKKLJOoasdlfj";
/**
* JWT生成Token.<br/>
* <p>
* JWT构成: header, payload, signature
*
* @param userId 登录成功后用户userId, 参数userId不可传空
*/
public static String createToken(String userId) throws Exception {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
//token 过期时间: 10天
nowTime.add(Calendar.DATE, 10);
//获得10天后的时间戳
Date expiresDate = nowTime.getTime();
// header(头部),头部信息主要包括(参数的类型--JWT,签名的算法--HS256)
Map<String, Object> map = Maps.newHashMap();
//加密算法
map.put("alg", "HS256");
//类型
map.put("typ", "JWT");
String token = JWT.create().withHeader(map)
// payload 存放的信息 iss jwt签发者
.withClaim("iss", "Service")
//接受该JWT的一方
.withClaim("aud", "APP").withClaim("userId", userId)
// sign time 开始时间
.withIssuedAt(iatDate)
// expire time 到期时间
.withExpiresAt(expiresDate)
// signature 签名
.sign(Algorithm.HMAC256(SECRET));
return token;
}
/**
* 解密Token
*
* @param token
* @return
* @throws Exception
*/
public static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
System.out.println("验证失败");
}
return jwt.getClaims();
}
/**
* 根据Token获取user_id
*
* @param token
* @return user_id
*/
public static String getAppUID(String token) {
Map<String, Claim> claims = verifyToken(token);
Claim user_id_claim = claims.get("userId");
if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
// token 校验失败, 抛出Token验证非法异常
}
assert user_id_claim != null;
return String.valueOf(user_id_claim.asString());
}
public static void main(String[] args) throws Exception {
String token = createToken("sssss");
//Map map = verifyToken(token);
String uuid = getAppUID(token);
System.out.println(uuid);
}
}