问题场景
今天在和前端对接接口的过程中,前端同事反馈说接口跨域了,我这边尝试调用线上接口发现实在正常的,拿到同事接口调用时的CUrl信息,通过postman调用也是正常的,看到发来的截图信息如下:
处理方案
这边提示是CORS错误,我们可以添加跨域配置,如下
package com.tianwu.operating.config;
/**
* 跨域请求配置类
*
*
* */
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
这边测试正常后,部署到测试环境,跨域问题也处理好了。
------------------------------------------------------------------------------------------------------------------------------
后续
这边在使用这个配置的时候,会出现同个controller接口有的正常访问,有的又报跨域问题,
原因分析
后面排查了很久,才注意到 CorsConfig 的同级还有一个登录过滤拦截器WebConfig,这么一来,问题也找到了,之所以会出现同个controller接口有的正常访问,有的又报跨域问题,是因为结果先被过滤器拦截下来了,没走到跨域配置。所以被拦截的接口都报了跨域问题。
解决思路
以后配置跨域先看下有没有拦截器存在,没得话可以直接添加上述的 CorsConfig ,如果存在,则在拦截器文件进行跨域配置,如下
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
// 过滤器跨域配置
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允许跨域的头部信息
config.addAllowedHeader("*");
// 允许跨域的方法
config.addAllowedMethod("*");
// 可访问的外部域
config.addAllowedOrigin("*");
// 需要跨域用户凭证(cookie、HTTP认证及客户端SSL证明等)
//config.setAllowCredentials(true);
//config.addAllowedOriginPattern("*");
// 跨域路径配置
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器,排除拦截路径
registry.addInterceptor(loginInterceptor()).excludePathPatterns(
接口地址);
}
}