周梦康 发表于 2021-04-14 275 次浏览

默认情况下

@CrossOrigin(origins = {"https://a.x.com", "https://b.x.com"})

实际遇到了如下场景:

通过监控 http 状态码,发现多了一些异常请求,通过排查发现前端组件可能被其他人在服务提供者不知情的情况下发布到了c.x.com域名下,,这时候只能修改代码

@CrossOrigin(origins = {"https://a.x.com", "https://b.x.com", "https://c.x.com"})

能不能支持这样

@CrossOrigin(origins = {"https://*.x.com"})

或者

@CrossOrigin(origins = {"*.x.com"})

因为目前控制器都是通过@RequestMapping来处理的,在DelegatingWebMvcConfiguration中可以重写RequestMappingHandlerMapping的跨域处理逻辑。

@Configuration
@EnableWebMvc
public class WebCorsConfig extends DelegatingWebMvcConfiguration {

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setCorsProcessor(new WebCorsProcessor());
        return handlerMapping;
    }

}
public class WebCorsProcessor extends DefaultCorsProcessor {

    /**
     * Check the origin of the request against the configured allowed origins.
     *
     * @param requestOrigin the origin to check
     * @return the origin to use for the response, or {@code null} which
     * means the request origin is not allowed
     */
    @Nullable
    public String checkOrigin(CorsConfiguration config, @Nullable String requestOrigin) {
        if (StringUtils.isEmpty(requestOrigin) || !StringUtils.hasText(requestOrigin)) {
            return null;
        }
        if (ObjectUtils.isEmpty(config.getAllowedOrigins())) {
            return null;
        }
        if (config.getAllowedOrigins().contains(CorsConfiguration.ALL)) {
            if (config.getAllowCredentials() != Boolean.TRUE) {
                return CorsConfiguration.ALL;
            } else {
                return requestOrigin;
            }
        }
        AntPathMatcher pathMatcher = new AntPathMatcher("|");
        for (String allowedOrigin : config.getAllowedOrigins()) {
            if (requestOrigin.equalsIgnoreCase(allowedOrigin)) {
                return requestOrigin;
            }
            if (pathMatcher.isPattern(allowedOrigin) && pathMatcher.match(allowedOrigin, requestOrigin)) {
                return requestOrigin;
            }
        }
        return null;
    }

}

后来发现有了新坑,前台出现了乱码,重写了 WebMvcConfigurerAdapter.extendMessageConverters的方法,问题得到解决

@Configuration
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
public class WebMvcAutoConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //解决中文字符集乱码的问题
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
    }
}

评论列表