Springboot实现跨域 - yiyixiaozhi/readingNotes GitHub Wiki

Springboot实现跨域

title: Springboot实现跨域 date: 2019-01-24 description: categories:

  • 工具 tags:

微信公众号:一一小知 问题或建议,请公众号留言

为了实现内网穿透,使用的frp。

请求链路:localhost前端—>云端服务器—>经frp穿透内网到localhost服务端。

在开发环境debug,访问云服务器遇到如下跨域问题:

xhr.js:178 OPTIONS http://114.116.44.87/user/login 403 (Forbidden)
:8080/#/login?redirect=%2Fdashboard:1 Access to XMLHttpRequest at 'http://114.116.44.87/user/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

看来是跨域被服务端阻止了。

服务端Springboot配置如下,参考官网配置方式实现:

@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("*");
            }
        };
    }
}

SpringSecurity需要设置允许跨域:

WebSecurityConfigurerAdapter实现类WebSecurityConfigconfigure方法中,需要允许跨域:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            //...踩坑了好久,终于记起来需要配置这里了
            //如果您使用的是Spring Security,请确保在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置。
            .and().cors()
            //...
    }
}

浏览器第一次会自动和服务器做一次通信。

Origin中的值主要有协议、域名、端口这几种。请求如下:

img

紧接着本地的第二次请求也被服务器通过了:

img

可以看到,服务器响应了数据:

img

参考网址:

⚠️ **GitHub.com Fallback** ⚠️