wanglizhong
2025-05-05 5390b4fc6d07efcb53d06b21454e6b24cad03a10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.ruoyi.framework.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.util.StringUtils;
 
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.service.ISysClientAppService;
 
/**
 * 匿名访问拦截器
 */
@Component
public class AnonymousInterceptor implements HandlerInterceptor {
 
    @Autowired
    private ISysClientAppService clientAppService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法,直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
 
        // 获取方法上的注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Anonymous anonymous = handlerMethod.getMethodAnnotation(Anonymous.class);
        
        // 如果方法上没有注解,则获取类上的注解
        if (anonymous == null) {
            anonymous = handlerMethod.getBeanType().getAnnotation(Anonymous.class);
        }
 
        // 如果没有注解,直接通过
        if (anonymous == null) {
            return true;
        }
 
        // 获取请求参数
        String appId = request.getParameter("appId");
        String sign = request.getParameter("sign");
        String timestamp = request.getParameter("timestamp");
        if(anonymous.needSign()){
            if(appId == null || sign == null || timestamp == null){
                throw new ServiceException("缺少必要参数");
 
            }
        }
        // 验证必要参数
        if (StringUtils.hasText(appId) && StringUtils.hasText(sign) && StringUtils.hasText(timestamp)) {
            // 验证签名
            if (clientAppService.validateSign(appId, sign, timestamp)) {
                return true;
            }
            throw new ServiceException("签名验证失败");
        }
 
        // 如果没有验证参数,也允许通过(适用于不需要验证的匿名接口)
        return true;
    }