package com.gear.common.utils.jwt; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JWTTokenUtils { public static String SECRET = "HUIYUAN-CORAL-PLATFORM"; public static String createToken(String userId,String phone,String client) { String token = null; try { //签发日期 Date iatDate = new Date(); //过期时间 Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.HOUR, 12); Date expirseDate = nowTime.getTime(); Map map = new HashMap(); map.put("alg", "HS256"); map.put("typ", "JWT"); token = JWT.create() .withIssuer(userId)//user实体 .withHeader(map)//jwt-header .withClaim("userId", userId) .withClaim("phone", phone) .withClaim("client",client) .withIssuedAt(iatDate)//设置签发时间 .withKeyId(userId) .withExpiresAt(expirseDate)//设置过期时间 .sign(Algorithm.HMAC256(SECRET));//加密 } catch (IOException e) { return token; } return token; } /** * 解密 * * @param token * @return */ public static String verifyToken(String token) throws Exception{ JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build(); DecodedJWT decodedJWT = jwtVerifier.verify(token); String userid = decodedJWT.getIssuer(); return userid; } }