1.为什么要 token自动续期
token中一般会包含用户的基本信息,为了保证token的安全性,一般会将token的过期时间设置的比较短,但是这样会导致用户因为token过期需要频繁登录,因此需要token自动续期。
2.如何实现token自动续期
登录时将token存入redis中,缓存有效期设置为 token有效时间的两倍(比token有效时间长即可)。
String token = JwtUtil.createToken(sysUser.getId(), user.getUserName());
redisUtil.set(sysUser.getPhone() + GlobalConstant.TOKEN, token, JwtUtil.EXPIRE_TIME*2);
在拦截器中重写public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)方法
private boolean refreshToken(SysUser sysUser) {
String token = request.getHeader(GlobalConstant.TOKEN);
String cacheToken = (String) (redisUtil.get(sysUser.getPhone() + GlobalConstant.TOKEN));
if (StringUtil.isEmpty(token)) {
logger.error("token不存在");
return false;
}
if (StringUtil.isEmpty(cacheToken)) {
logger.error("用户未登录");
return false;
}
try {
JwtUtil.verify(token);
} catch (TokenExpiredException tokenExpiredException) {
if (redisUtil.hasKey(sysUser.getPhone() + GlobalConstant.TOKEN)) {
String newToken = JwtUtil.createToken(sysUser.getId(), sysUser.getUserName());
redisUtil.set(sysUser.getPhone() + GlobalConstant.TOKEN, newToken, JwtUtil.EXPIRE_TIME * 2);
return true;
}
} catch (Exception e) {
logger.error("token不合法");
return false;
}
return true;
}
JwtUtil工具类如下
import com.admin.common.constant.GlobalConstant;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
public class JwtUtil {
public static final String TOKEN_SECRET_KEY = "tokenSecretKey";
public static final int EXPIRE_TIME = 60;
public static String createToken(Long userId, String userName) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, EXPIRE_TIME);
return JWT.create()
.withAudience(userId + "")
.withClaim("userName", userName)
.withIssuedAt(new Date())
.withExpiresAt(calendar.getTime())
.sign(Algorithm.HMAC256(TOKEN_SECRET_KEY));
}
public static void verify(String token) {
JWT.require(Algorithm.HMAC256(TOKEN_SECRET_KEY)).build().verify(token);
}
public static Long getUserIdByToken(HttpServletRequest request) {
String token = request.getHeader(GlobalConstant.TOKEN);
String userId = JWT.decode(token).getAudience().get(0);
return Long.valueOf(userId);
}
}
|