Springboot interceptor injection failure leads to cross-domain

Uncle Cthulhu 2022-11-24 21:24:31 阅读数:56

springbootinterceptorinjectionfailureleads

1. ProcureInterceptor


import static com.construn.procure.common.Variable.SECRETPC;
import static com.construn.procure.common.Variable.SECRETWAP;
import static com.construn.procure.common.Variable.TOKEN;
import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS;
import com.alibaba.fastjson.JSON;
import com.construn.procure.constant.Num;
import com.construn.procure.dao.TokenDao;
import com.construn.procure.entity.Token;
import com.construn.procure.util.TokenUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* @author chaosgod 2019-02-27 11:24
* @return
* @description :
*/
@Slf4j
@Component
public class ProcureInterceptor implements HandlerInterceptor {
@Autowired
private TokenUtils tokenUtils;
@Autowired
private TokenDao tokenDaoImpl;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("拦截器ProcureInterceptor:*******************************");
String[] noFilters =
new String[]{
"login",
"sendMsg",
"errorQuest"
};
String uri = request.getRequestURI();
boolean beFilter = true;
log.info("请求地址uri:{}", uri);
log.info("请求方式:{}", request.getMethod());
// 预请求
if (OPTIONS.toString().equals(request.getMethod())) {
response.setHeader("Access-Control-Allow-Origin", "*");
// 单独写get/put/delete/post
// 直接写 * Access is not supported in other browsers.*不代表全部
response.setHeader("Access-Control-Allow-Methods", "GET,PUT,DELETE,POST,OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader(
"Access-Control-Allow-Headers",
"Authentication,Origin, X-Requested-With, " + "Content-Type, Accept,token");
return true;
}
// 配置跨域
response.setHeader("Access-Control-Allow-Origin", "*");
String requestId = request.getHeader("X-REQUEST-ID");
String userAgent = request.getHeader("User-Agent");
if (requestId != null) {
MDC.put("requestUUID", requestId);
}
if (userAgent != null) {
MDC.put("User-Agent", userAgent);
}
String userId = "non-user";
MDC.put("userId", userId);
log.info("变量:{}", JSON.toJSONString(request.getParameterMap()));
for (String s : noFilters) {
String[] ss = uri.split("/");
if (s.equals(ss[ss.length - 1]) || s.equals(ss[ss.length - 2])) {
beFilter = false;
log.error("Contains no-go interceptors:{}", s);
break;
}
}
String origin = request.getHeader("Origin");
log.info("request receivedOrigin为:{}", origin);
if (beFilter) {
log.info("toke验证通过√ √ √ √ √ √ √ √ √ √ √ √ √ √");
MDC.put("userId", userId);
Variable.userSession.set(token);
return true;
}
return true;
}
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) {
}
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// TODO Auto-generated method stub
}
}

2. WebAppConfig

package com.construn.procure.common;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke @Date: 2018/8/16 on 下午2:25
* @description: 让 springBoot Know that there is this interceptor extends WebMvcConfigurationSupport Occasionally it loads successfully implements
* WebMvcConfigurer will not run directly
*/
@Slf4j
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Bean
ProcureInterceptor getProcureInterceptor() {
return new ProcureInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
log.info("WebAppConfigInterceptor injected successfully");
registry.addInterceptor(getProcureInterceptor()).addPathPatterns("/**");
// 对来自/user/** The request from this link is intercepted;
// registry.addInterceptor(getInterfaceAuthCheckInterceptor()
// This way no matter what the situation is
// registry.addInterceptor(new InterfaceAuthCheckInterceptor())
// 这种情况时,自定义的interceptorNo other content can be injected into the ,比如redis或者其他service,如果要注入,The method above must be used
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.maxAge(3600);
}
private CorsConfiguration addCorsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
List<String> list = new ArrayList<>();
list.add("*");
corsConfiguration.setAllowedOrigins(list);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", addCorsConfig());
return new CorsFilter(source);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("Static file injection was successful");
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry
.addResourceHandler("/swagger-resources/**")
.addResourceLocations("classpath:/META-INF/resources/swagger-resources/");
registry
.addResourceHandler("/swagger/**")
.addResourceLocations("classpath:/META-INF/resources/swagger*");
registry
.addResourceHandler("/v2/api-docs/**")
.addResourceLocations("classpath:/META-INF/resources/v2/api-docs/");
}
/**
* @return void
* @author chaosgod 2018/10/17 上午11:34
* @description : Configure access to static files
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
log.info("Access to static files is successfully injected");
configurer.enable();
// super.configureDefaultServletHandling(configurer);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("JsonThe format injection was successful");
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.PrettyFormat,
SerializerFeature.DisableCircularReferenceDetect);
// 3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
// 4.在convert中添加配置信息.
converter.setSupportedMediaTypes(fastMediaTypes);
converter.setFastJsonConfig(config);
// 5.将convert添加到converters当中.
converters.add(converter);
// super.configureMessageConverters(converters);
// SerializerFeature.WriteNullListAsEmpty:List类型字段为null时输出[]而非null
// SerializerFeature.WriteMapNullValue:Show empty fields
// SerializerFeature.WriteNullStringAsEmpty:String type fields are null时输出""而非null
// SerializerFeature.WriteNullBooleanAsFalse:Boolean类型字段为null时输出false而null
// SerializerFeature.PrettyFormat:美化json输出,Otherwise it is output as a whole line
}
}

3. 包

4. 启动提示

5. Check whether other configuration classes and implements WebMvcConfigurer是否有冲突,

6. Finally checked outswaggerUIThe configuration class is using the extends WebMvcConfigurationSupport这种方式,导致冲突,

改为public class SwaggerConfig implements WebMvcConfigurer {This way it starts normally..

copyright:author[Uncle Cthulhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/328/202211242120377174.html