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;
|
}
|
}
|