在我们的开发项目中,经常需要用到用户ID,比如在小程序商城系统中,我们将商品加入购物车,这时前端就需要发送请求,携带上用户的ID。基本上很多种请求操作都需要携带用户ID,如果每个请求都需要我们往data中添加id的话,那样需要写很多重复代码,并且代码也不美观;所以我们可以利用JWT跟注解的方式来实现;
一、编写token管理器
1.1、导入jwt包
在maven中加入该依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.1</version> </dependency>
1.2、创建JwtHelper,用于创建和验证token
package com.maomao.demo.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.*; public class JwtHelper { //秘钥 public static final String SECRET = "hdriverbird-token"; //签名是由谁生成的 public static final String ISSUSER = "hdriverbird"; //签名的主题 public static final String SUBJECT = "token test"; //观众 public static final String AUDIENCE = "miniapp"; public String createToken(String userId) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); Map<String, Object> m = new HashMap<>(); m.put("alg", "HS256"); m.put("typ", "JWT"); //签名时间 Date nowDate = new Date(); //过期时间Date对象 Date expire = getAfterDate(nowDate, 0, 0, 0, 1, 0, 0); String token = JWT.create(). //设置头部 withHeader(m) // 设置 载荷 Payload .withClaim("userId", userId) .withIssuer(ISSUSER) .withSubject(SUBJECT) .withAudience(AUDIENCE) //签名时间 .withIssuedAt(nowDate) //过期时间 .withExpiresAt(expire) .sign(algorithm); return token; }catch (JWTCreationException exception){ exception.printStackTrace(); } return null; } /** * 验证token * @return */ public String verifyToken(String token){ try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier build = JWT.require(algorithm) .withIssuer(ISSUSER) .build(); DecodedJWT verify = build.verify(token); //获取声明信息 Map<String, Claim> claims = verify.getClaims(); Claim claim = claims.get("userId"); //转为字符串 return claim.asString(); }catch (JWTCreationException e){ e.printStackTrace(); } return ""; } //获取某个时间点的日期对象 public Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second) { if (date == null) { date = new Date(); } Calendar cal = new GregorianCalendar(); cal.setTime(date); if (year != 0) { cal.add(Calendar.YEAR, year); } if (month != 0) { cal.add(Calendar.MONTH, month); } if (day != 0) { cal.add(Calendar.DATE, day); } if (hour != 0) { cal.add(Calendar.HOUR_OF_DAY, hour); } if (minute != 0) { cal.add(Calendar.MINUTE, minute); } if (second != 0) { cal.add(Calendar.SECOND, second); } return cal.getTime(); } }