53 lines
1.8 KiB
Java
53 lines
1.8 KiB
Java
package com.example.caseData.middlewares;
|
|
|
|
import com.example.caseData.config.AppConfig;
|
|
import com.example.caseData.config.JwtConfig;
|
|
import com.example.caseData.exception.BusinessException;
|
|
import com.example.caseData.utils.EnvUtil;
|
|
import com.example.caseData.utils.JwtUtil;
|
|
import io.jsonwebtoken.Claims;
|
|
import io.jsonwebtoken.ExpiredJwtException;
|
|
import io.jsonwebtoken.Jwts;
|
|
import jakarta.annotation.Resource;
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
import org.jetbrains.annotations.NotNull;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import java.util.Base64;
|
|
|
|
@Component
|
|
public class JwtInterceptor extends BaseInterceptor {
|
|
@Resource
|
|
private JwtUtil jwtUtil;
|
|
|
|
@Override
|
|
public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
|
|
// 放行白名单路径
|
|
if (isWhiteListed(request)) {
|
|
return true;
|
|
}
|
|
|
|
String token = request.getHeader("Authorization");
|
|
|
|
if (token != null && token.startsWith("Bearer ")) {
|
|
try {
|
|
token = token.substring(7); // 去除 "Bearer " 前缀
|
|
Claims claims = jwtUtil.verifyToken(token);
|
|
|
|
// 将解析出来的数据放入请求属性中供后续使用
|
|
request.setAttribute("userId", claims.get("user_id"));
|
|
|
|
return true;
|
|
} catch (ExpiredJwtException e) {
|
|
throw new BusinessException("406","token过期");
|
|
} catch (Exception e) {
|
|
throw new BusinessException("405","token错误");
|
|
}
|
|
} else {
|
|
throw new BusinessException("405","请求未授权");
|
|
}
|
|
}
|
|
}
|