步骤一:定义新的Request
package com.ict.lux.framework.interceptor;import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;public class EnhancedHttpRequest extends HttpServletRequestWrapper
{private final Map<String, String[]> modifiableParameters;private Map<String, String[]> allParameters = null;public EnhancedHttpRequest (final HttpServletRequest request, final Map<String, String[]> additionalParams){super(request);modifiableParameters = new TreeMap<>();modifiableParameters.putAll(additionalParams);}@Overridepublic String getParameter(final String name){String[] strings = getParameterMap().get(name);if (strings != null){return strings[0];}return super.getParameter(name);}@Overridepublic Map<String, String[]> getParameterMap(){if (allParameters == null){allParameters = new TreeMap<>();allParameters.putAll(super.getParameterMap());allParameters.putAll(modifiableParameters);}return Collections.unmodifiableMap(allParameters);}@Overridepublic Enumeration<String> getParameterNames(){return Collections.enumeration(getParameterMap().keySet());}@Overridepublic String[] getParameterValues(final String name){return getParameterMap().get(name);}
}
步骤二:拦截器使用
package com.ict.lux.framework.interceptor;import cn.hutool.core.util.StrUtil;
import com.ict.lux.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;/*** 共有auth认证(认证内部调用接口)** @author chensir* @date 2024/10/15*/
@Component
public class PublicAuthInterceptor implements HandlerInterceptor {private final AuthProperties authProperties;@Autowiredpublic PublicAuthInterceptor(AuthProperties authProperties) {this.authProperties = authProperties;}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String secretKey = authProperties.getSecretKey();String interiorToken = request.getHeader("token");// 检查请求头authToken秘钥是否正确if (StrUtil.isNotBlank(interiorToken) && secretKey.equals(interiorToken)) {Map<String, String[]> additionalParams = new HashMap<>();additionalParams.put("chensir", new String[] {"您好"});additionalParams.put("uid", new String[] {"123"});EnhancedHttpRequest enhancedHttpRequest = new EnhancedHttpRequest((HttpServletRequest) request, additionalParams);return true;}return true;}
}