LoginResponseDTO responseDTO = new LoginResponseDTO(); // 先从redis中取token Object redisUserToken = redisTemplate.opsForHash().get(CommonConstant.TOKEN, mbrInfoDTO.getMbrId()); //如果redis中没有此token 就创建个新token if (null == redisUserToken || "".equals(redisUserToken) || null == JwtUtils.decodeToken(String.valueOf(redisUserToken))) { Map<String, Object> Claims = new HashMap<>(); mbrInfoDTO.setCpPwd(""); //把查出来的数据装进 token中 Claims.put("user", mbrInfoDTO); redisUserToken = JwtUtils.createToken(Claims, CommonConstant.TOKEN_PREFIX); //把创建的token 装到redis redisTemplate.opsForHash().put(CommonConstant.TOKEN, mbrInfoDTO.getMbrId(), redisUserToken); } //最后返回 token responseDTO.setToken(redisUserToken.toString());
/** 枚举
public static final String TOKEN = "token";
// token的过期时间
public static final int TOKEN_PREFIX = 1000 * 60 * 60 * 24 * 7;
public static final String KIDARI_ISSUER = "kidari_issuer";
public static final String USER_ID = "user_id";
// token的生成工具类
public static String createToken(Map<String, Object> claims, long prefixTime) { // 生成了一个 JWT 令牌(未签名) String token = Jwts.builder() .setId(CommonConstant.USER_ID) .setIssuer(CommonConstant.KIDARI_ISSUER) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + prefixTime)) .addClaims(claims) .signWith(getSecretKey()) .compact(); return token; } public static Claims decodeToken(String token) { try { // 令牌解码 return Jwts.parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token).getBody(); } catch (ExpiredJwtException e) { log.info(token + "Token已过期"); } catch (Exception e) { log.error(e.getMessage()); } return null; }
/** * 从配置文件中获取加密key,并构造SecretKey对象返回 * * @return SecretKey */ public static SecretKey getSecretKey() { // 生成Jwt的时间 return Keys.hmacShaKeyFor(Decoders.BASE64.decode(CommonConstant.SECRET_KEY)); }