在《用户登录页接口》中提到 Controller 类中的 Handle 方法接收到 Mybatis 返回的查询结果,通过使用Jwt来实现token计算并将计算结果返回给前端。这里记录使用 Jwt 实现token 计算的方法,世纪使用时直接复制本文代码即可。
引入依赖 1 2 3 4 5 <dependency > <groupId > io.jsonwebtoken</groupId > <artifactId > jjwt</artifactId > <version > 0.9.1</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 65 66 67 68 69 70 71 72 73 74 75 76 77 public class JwtUtil { public static final Long JWT_TTL = 60 * 60 *1000L ; public static final String JWT_KEY = "sangeng" ; public static String createJWT (String id, String subject, Long ttlMillis) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); if (ttlMillis==null ){ ttlMillis=JwtUtil.JWT_TTL; } long expMillis = nowMillis + ttlMillis; Date expDate = new Date(expMillis); SecretKey secretKey = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setSubject(subject) .setIssuer("sg" ) .setIssuedAt(now) .signWith(signatureAlgorithm, secretKey) .setExpiration(expDate); return builder.compact(); } public static SecretKey generalKey () { byte [] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); SecretKey key = new SecretKeySpec(encodedKey, 0 , encodedKey.length, "AES" ); return key; } public static Claims parseJWT (String jwt) throws Exception { SecretKey secretKey = generalKey(); return Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(jwt) .getBody(); } public static void main (String[] args) throws Exception { String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "sangeng" , null ); System.out.println(token); Claims claims = JwtUtil.parseJWT(token); String subject = claims.getSubject(); System.out.println(subject); } }
Controller 类中使用上述类的静态方法 注意:传入的参数列表是 (String, String, Long) 需要转换
1 String token = JwtUtil.createJWT(UUID.randomUUID().toString(), String.valueOf(loginUser.getId()), null );