package com.yuanchu.tms.utils;
|
|
import com.auth0.jwt.JWT;
|
import com.auth0.jwt.JWTVerifier;
|
import com.auth0.jwt.algorithms.Algorithm;
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
import org.springframework.stereotype.Component;
|
|
import java.util.Calendar;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
@Component
|
public class Jwt {
|
private final String SECRET = "value";
|
|
public String createJwt(String name,int id, int time) {
|
HashMap<String, Object> headers = new HashMap<>();
|
Calendar expires = Calendar.getInstance();
|
expires.add(Calendar.MINUTE, time);
|
String jwtToken = JWT.create()
|
// 第一部分Header
|
.withHeader(headers)
|
// 第二部分Payload
|
.withClaim("name", name)
|
.withClaim("id", id)
|
.withExpiresAt(expires.getTime())
|
// 第三部分Signature
|
.sign(Algorithm.HMAC256(SECRET));
|
return jwtToken;
|
}
|
|
public Map<String, String> readJWT(String token) {
|
Map<String, String> map = new HashMap<>();
|
map.put("state", "0");
|
map.put("info", "正常");
|
map.put("data", null);
|
// 创建一个验证的对象
|
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
|
DecodedJWT verify;
|
try {
|
verify = jwtVerifier.verify(token);
|
Map<String, String> maps = new HashMap<>();
|
maps.put("id",verify.getClaim("id").toString());
|
maps.put("name",verify.getClaim("name").toString());
|
map.put("data", JackSonUtil.marshal(maps));
|
} catch (Exception e) {
|
String info = ("" + e).contains("expired") ? "已过期" : "无效签名";
|
String state = ("" + e).contains("expired") ? "1" : "2";
|
map.put("state", state);
|
map.put("info", info);
|
}
|
return map;
|
}
|
|
}
|