一. 引入JAR包
1 2 3 4 5 6 7 8 9 10 | < dependency > < groupId >com.auth0</ groupId > < artifactId >java-jwt</ artifactId > < version >4.4.0</ version > </ dependency > < dependency > < groupId >com.alibaba.fastjson2</ groupId > < artifactId >fastjson2</ artifactId > < version >2.0.45</ version > </ dependency > |
二. 创建JWT工具类
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 | public class JWTUtils { /** token秘钥,请勿泄露 */ public static final String SECRET = "#@$_&^#@DSWER#@" ; /** * * @param userName : 用户名 * @return 生成的字符串Token值 */ public static String createToken(String userName) { Date iatDate = new Date(); // expire time Calendar nowTime = Calendar.getInstance(); // nowTime.add(Calendar.SECOND, 1 * 24 * 60 * 60); nowTime.add(Calendar.SECOND, 1 * 24 * 60 * 60 ); //一天过期 //过期时间1天 Date expiresDate = nowTime.getTime(); // header Map Map<String, Object> map = new HashMap<>(); map.put( "alg" , "HS256" ); map.put( "typ" , "JWT" ); // build token // param backups {iss:Service, aud:APP} String token = JWT.create().withHeader(map) // header .withClaim( "iss" , "Service" ) // payload .withClaim( "aud" , "APP" ) .withClaim( "userName" , null == userName ? null : userName) .withIssuedAt(iatDate) // sign time .withExpiresAt(expiresDate) // expire time .sign(Algorithm.HMAC256(SECRET)); // signature return token; } /** * 解密Token * * @param token: 服务器端生成的Token发送给客户端,客户端再传递过来需要验证的Token * @return 返回验证结果: code:{0:success, 1:fail} */ public static Map<String,Object> verifyToken(String token) { Map<String, Claim> claims = null ; Map<String,Object> map = new HashMap<>(); map.put( "code" , 1 ); //默认为验证失败 0: 验证成功 try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build(); claims = verifier.verify(token).getClaims(); map.put( "code" , 0 ); map.put( "msg" , "success" ); } catch (SignatureVerificationException e){ map.put( "msg" , "签名无效" ); } catch (AlgorithmMismatchException e){ map.put( "msg" , "签名算法不匹配" ); } catch (TokenExpiredException e){ map.put( "msg" , "token过期" ); } map.put( "claims" ,claims); return map; } } |
二. 生成及验证测试
1 2 3 4 5 6 7 8 9 | public static void main(String[] args) { //生成Token, 登陆成功后,将生成的Token返回给客户端 String token = JWTUtils.createToken( "xiaomi" ); //收到客户端通过ajax传递过来的token,将验证结果返回给用户 //客户将根据这里返回的code,msg进行判断验证 String json = JSON.toJSONString(JWTUtils.verifyToken(token)); //使用阿里的fastjson2类 System.out.println(json); } |