package com.example.springboot.intereptor;
import com.alibaba.fastjson.JSONObject;
import com.example.springboot.pojo.Result;
import com.example.springboot.utils.JwtUntil;
import io.jsonwebtoken.lang.Strings;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
@Slf4j
public class CheckInterceptor implements HandlerInterceptor {
// 要实现HandlerInterceptor类 并重写 里面的的方法
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
String url = req.getRequestURI();//获取请求头的地址
log.info("路径:{}",url);
if (url.contains("/login")) {
log.info("登录操作放行....");
return true; // true 放行
}
// 获取header 中为Authorization 的东西
//我前端设置的是Authorization 设置token 就token
String token = req.getHeader("Authorization");
log.info("前端令牌:{}",token);
if(!Strings.hasLength(token)){//如果不存在
log.info("用户令牌不存在");
Result error = Result.error("404","身份过期,请重新登录");
//阿里巴巴手动转JSON文件
String noLogin = JSONObject.toJSONString(error);
resp.getWriter().write(noLogin); //显示在页面
return false;
}
try {
JwtUntil.parseJwt(token);
} catch (Exception e) {
log.info("令牌解析报错。。。");
Result error = Result.error("404","身份过期,请重新登录");
//阿里巴巴手动转JSON文件
String noLogin = JSONObject.toJSONString(error);
resp.getWriter().write(noLogin); //显示在 页面
return false;
}
//所有通过放行
return true;
}
// 每次 开始会执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
System.out.println("postHandle/....");
}
//结束会自动销毁
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
System.out.println("afterCompletion/....");
}
}
前端请求效验Jwt令牌
最新推荐文章于 2024-09-02 12:54:06 发布