- 一、通过token获取用户信息
- 二、验证token过期
代码位置:com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter
直接上代码:
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
@Autowired
private TokenService tokenService;
//做内部过滤
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
{
tokenService.verifyToken(loginUser);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//上下文设置新的认证
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
chain.doFilter(request, response);
}
}
- 打上断点详细看看
- 先看看前端的请求头:Authorization就是token了
- 断点方法getLoginUser()
public LoginUser getLoginUser(HttpServletRequest request)
{
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
try
{
//从令牌中获取数据声明====解析成对象
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);//登录用户 redis key+uuid
LoginUser user = redisCache.getCacheObject(userKey);//获取缓存中的用户信息
return user;
}
catch (Exception e)
{
}
}
return null;
}
- 先看看获取请求头header
- 清空token前缀----为什么清除呢?后面会用到剩下的内容进行解析,然后去查缓存
- 还是断点方法中,开始解析剩下的token
- 进入解析令牌方法
- 解析结束后的claims
- 合成用户缓存的key,然后从redis中查出这个用户的信息
- 验证过期verifyToken
public void verifyToken(LoginUser loginUser)
{
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
{
refreshToken(loginUser);
}
}
- 获取过期时间expireTime
- 刷新令牌===重新设置缓存过期时间
- 可以看到过期时间发生了改变
剩下就是重新设置spring security的认证信息了,之前走过登录的,那些信息差别不大。
- 之后spring security剩下的过滤器链中帮我们更新头部信息
- 更新上下文信息
剩下也没什么了,遇到再说~~w(゚Д゚)w



