整合作业
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package com.ycjy.config;
|
||||
|
||||
import com.ycjy.common.JwtUtil;
|
||||
import com.ycjy.dao.Product;
|
||||
import com.ycjy.service.ProductService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
@Component
|
||||
public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Autowired
|
||||
private ProductService productService;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String method = request.getMethod();
|
||||
String uri = request.getRequestURI();
|
||||
String auth = request.getHeader("Authorization");
|
||||
|
||||
// 已登录就把 username 放进 request,供 Controller 取用
|
||||
Claims claims = parse(auth);
|
||||
if (claims != null) {
|
||||
request.setAttribute("username", claims.get("username", String.class));
|
||||
}
|
||||
|
||||
// 删除商品必须登录
|
||||
if ("DELETE".equalsIgnoreCase(method) && uri.matches(".*/api/product/\\d+$")) {
|
||||
if (claims == null) {
|
||||
response.setStatus(401);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 下载商品价格 > 5000 必须登录
|
||||
if ("GET".equalsIgnoreCase(method) && uri.matches(".*/api/product/\\d+/download$")) {
|
||||
String idStr = uri.replaceAll(".*/api/product/(\\d+)/download$", "$1");
|
||||
Product product = productService.getById(Integer.valueOf(idStr));
|
||||
if (product != null && product.getPrice() > 5000 && claims == null) {
|
||||
response.setStatus(401);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// 解析 token,失败返回 null
|
||||
private Claims parse(String auth) {
|
||||
if (auth == null || !auth.startsWith("Bearer ")) return null;
|
||||
return JwtUtil.parse(auth.substring(7));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user