在做后台管理系统的时候,登录是再正常不过了。那么,在登录之后,请求一系列的接口是需要使用token的。那么,问题就出来了,在最开始的登录阶段,登录是不需要token。那我们在登录之后,请求每一个接口我们总不能每一次都在方法中去写获取请求头,然后判断token,这是不合理的。
最有效或者最有用的解决方案就是写一个过滤器,让每一个请求的接口都获取请求头,判断……这一切都在过滤器中完成。然而,在过滤器中,我们还需要踢除登录的接口。
package com.bnc.s99.filter;import com.bnc.s99.common.RedisClass;
import com.bnc.s99.utils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Objects;import static org.hibernate.internal.util.collections.ArrayHelper.indexOf;@Component
public class MyFilter implements Filter {@Autowiredprivate RedisClass redisClass;@Overridepublic void init(FilterConfig filterConfig) {}@Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;String uri = req.getRequestURI();//在uriArr 的数组中存放的就是不需要经过 过滤器的接口//也就是说,当请求这数组中的接口时就会自动跳过,不需要经过这过滤器String[] uriArr = new String[]{"/admin/login","/admin/loginOut","/admin/getCode","/admin/test"};int index = indexOf(uriArr , uri);if (index != -1) {chain.doFilter(request, response);return;}String headerToken = req.getHeader("token");if(headerToken == null) {resp.setStatus(403); // 403 Forbiddenresp.setContentType("application/json");resp.setCharacterEncoding("UTF-8");try (PrintWriter out = resp.getWriter()) {// 创建一个简单的JSON响应体String jsonResponse = "{\"error\": \"没有token\" , \"code\": \"403\" , \"data\": null}";out.write(jsonResponse);}return;}Boolean bol = JwtUtil.isTokenExpired(headerToken);if(bol){resp.setStatus(403); // 403 Forbiddenresp.setContentType("application/json");resp.setCharacterEncoding("UTF-8");try (PrintWriter out = resp.getWriter()) {// 创建一个简单的JSON响应体String jsonResponse = "{\"error\": \"token已过期\" , \"code\": \"403\" , \"data\": null}";out.write(jsonResponse);}return;}Map userinfo = JwtUtil.parseToken(headerToken);String username = userinfo.get("username").toString();String redisToken = redisClass.getString(username);if(Objects.equals(redisToken, headerToken)){resp.setStatus(403); // 403 Forbiddenresp.setContentType("application/json");resp.setCharacterEncoding("UTF-8");try (PrintWriter out = resp.getWriter()) {// 创建一个简单的JSON响应体String jsonResponse = "{\"error\": \"token已注销\" , \"code\": \"403\" , \"data\": null}";out.write(jsonResponse);}return;}chain.doFilter(request, response);}@Overridepublic void destroy() {}
}