1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map;
public class JwtToken {
private static final String SECRET = "simon";//公用私密
/** * 生成token * * @param object * @param minute * @return * @throws Exception */ public static String createToken(Object object, Integer minute) throws Exception { //签发时间 Date iaDate = new Date();
//TODO 转换加密对象 User user=(User)object;
//过期时间 - 一分钟过期 Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.MINUTE, minute); Date expiresDate = nowTime.getTime();
Map<String, Object> map = new HashMap<>(); map.put(PublicClaims.ALGORITHM, "HS256"); map.put(PublicClaims.TYPE, "JWT");
String token = JWT.create() .withHeader(map)//TODO .withClaim("id",user.getId()) .withExpiresAt(expiresDate)//设置过期时间,过期时间大于签发时间 .withIssuedAt(iaDate)//设置签发时间 .sign(Algorithm.HMAC256(SECRET));//加密
return token; }
/** * 解密token * * @param token * @return * @throws Exception */ public static Map<String, Claim> verifyToken(String token) throws Exception { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build(); try { DecodedJWT verify = verifier.verify(token); return verify.getClaims(); } catch (Exception e) { throw new RuntimeException("Illegal request"); } } }
|