token过期自动续费方案和实现

时间:2024-12-18 07:43:41
package com.liu.token.filter; import com.alibaba.fastjson.JSON; import com.liu.token.common.CustomException; import com.liu.token.utlis.JwtUtil; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.springframework.util.AntPathMatcher; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @Slf4j @WebFilter public class LoginFilter implements Filter { // 路径匹配器 public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher(); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; //1、获取本次请求的URI String requestURI = request.getRequestURI(); log.info("拦截到请求:{}", requestURI); // 定义不需要处理的请求路径 String[] urls = new String[]{ "/user/login" }; //2、判断本次请求是否需要处理 boolean check = check(urls, requestURI); //3、如果不需要处理,则直接放行 if (check) { log.info("本次请求{}不需要处理", requestURI); filterChain.doFilter(request, response); return; } String access_token = request.getHeader("access_token"); String refresh_token = request.getHeader("refresh_token"); if (access_token==null||refresh_token==null){ throw new CustomException("没有登录,请登录!"); } HashMap<String,Object> map = new HashMap(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); try { // 过期了会报错,就会执行catch代码块 Claims claims = JwtUtil.parseJWT(access_token); } catch (Exception e) { try { Claims claims = JwtUtil.parseJWT(refresh_token); System.out.println(claims); String id = claims.get("sub").toString(); String jwt = JwtUtil.createJWT(id, 60 * 1000l); map.put("code",401); map.put("msg","刷新token"); map.put("data",jwt); response.getWriter().write(JSON.toJSONString(map)); response.getWriter().close(); } catch (Exception ex) { map.put("code",402); map.put("msg","token已经过期,请重新登录!"); map.put("data",null); response.getWriter().write(JSON.toJSONString(map)); response.getWriter().close(); } } filterChain.doFilter(request, response); } /** * 路径匹配,检查本次请求是否需要放行 * * @param urls * @param requestURL * @return */ public boolean check(String[] urls, String requestURL) { for (String url : urls) { boolean match = PATH_MATCHER.match(url, requestURL); if (match) { return true; } } return false; } }