带有HTTPS的Spring Boot CORS失败 [英] Spring Boot CORS with HTTPS failing

查看:108
本文介绍了带有HTTPS的Spring Boot CORS失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot通过Angular应用程序提供一个简单的REST控制器.我配置了一个全局CORS策略:

I am using Spring Boot to serve a simple REST controller with an Angular app. I configured a global CORS policy:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "PUT", "POST", "PATCH", "OPTIONS");
        }
    };
}

现在,在使用纯HTTP时,此方法工作正常,但是,如果我在 application.properties 中配置TLS,如下所示:

Now this works fine when using plain HTTP, however if I configure TLS in the application.properties like this:

server.port=8443
server.ssl.key-store=src/main/resources/keystore.p12
server.ssl.key-store-password=password
server.ssl.key-store-type=PKCS12

请求被阻止.角度控制台向我显示CORS失败.

The requests are blocked. The angular console shows me, that the CORS failed.

为什么在调用 https://localhost:8443/test 时失败,但是在调用 http://localhost:8080/test 且未配置TLS?

Why does it fail when calling https://localhost:8443/test but succeeds when calling http://localhost:8080/test and no TLS configured?

我阅读了完整的文档.

这是控制台记录的错误消息:

Here is the error message that the console logs:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8443/test. (Reason: CORS request did not succeed).

推荐答案

在类级别进行cors配置,如下所示(明确使Allow Cors-Origin成为):

Make a cors configuration in Class level Like this (which explicitly make Allow Cors-Origin):

        @Component
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public class MyCorsConfig implements Filter {

            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                final HttpServletResponse response = (HttpServletResponse) res;
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
                response.setHeader("Access-Control-Max-Age", "3600");
                if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
                    response.setStatus(HttpServletResponse.SC_OK);
                } else {
                    chain.doFilter(req, res);
                }
            }

            @Override
            public void destroy() {
            }

            @Override
            public void init(FilterConfig config) throws ServletException {
            }
        }

这篇关于带有HTTPS的Spring Boot CORS失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆