【JAVA】JWT token verification code

Uncle Cthulhu 2022-11-24 21:24:55 阅读数:909




2. class

/*** Created with IntelliJ IDEA.** @author: zhangenke* @Date: 2018/8/29 on 10:50 AM* @description:*/public class TestUtils {/*** Token secret key, please do not disclose, please do not modify backups:JKKLJOoasdlfj* Others have tampered with the data, but the signature key is stored on the server, the key is different, and the generated sign is also different.* So you can know whether the data has been tampered with according to the difference of the sign.*/private static final String SECRET = "JKKLJOoasdlfj";/*** JWT generates Token.

* JWT composition: header, payload, signature** @param userId UserId after successful login, the parameter userId cannot be passed empty*/public static String createToken(String userId) throws Exception {Date iatDate = new Date();// expire timeCalendar nowTime = Calendar. getInstance();//token expiration time: 10 daysnowTime.add(Calendar.DATE, 10);//Get the timestamp after 10 daysDate expiresDate = nowTime. getTime();// header (head), the header information mainly includes (parameter type--JWT, signature algorithm--HS256)Map map = Maps. newHashMap();//Encryption Algorithmmap. put("alg", "HS256");//typemap. put("typ", "JWT");String token = JWT.create().withHeader(map)// information stored in payload iss jwt issuer.withClaim("iss", "Service")//The party that accepts the JWT.withClaim("aud", "APP").withClaim("userId", userId)// sign time start time.withIssuedAt(iatDate)// expire time expiration time.withExpiresAt(expiresDate)// signature signature.sign(Algorithm.HMAC256(SECRET));return token;}/*** Decrypt Token** @param token* @return* @throws Exception*/public static Map 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("Authentication failed");}return jwt. getClaims();}/*** Get user_id according to Token** @param token* @return user_id*/public static String getAppUID(String token) {Map claims = verifyToken(token);Claim user_id_claim = claims. get("userId");if (null == user_id_claim || StringUtils. isEmpty(user_id_claim. asString())) {// Token verification failed, throwing Token verification illegal exception}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);}}

copyright:author[Uncle Cthulhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/328/202211242120378606.html