参考
相关链接: 操作示例.
问题
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://dev-lark-mgr.jd.com", "http://beta-lark-mgr.jd.com", "http://lark-mgr.jd.com")
//是否允许证书 不再默认开启
.allowCredentials(true)
.allowedHeaders("*")
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
场景:只有带有Token的情况下该方案起作用
原因:
只有执行到具体的Handler,跨域配置才可能生效
如果有前置过滤器,认证失败返回,则CORS配置没有机会生效,整体路径
org.springframework.web.servlet.DispatcherServlet#doDispatch
handler获取
org.springframework.web.servlet.handler.AbstractHandlerMapping#getHandler
@Override
@Nullable
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (logger.isTraceEnabled()) {
logger.trace("Mapped to " + handler);
}
else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
logger.debug("Mapped to " + executionChain.getHandler());
}
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
// 关键分析路径
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}