Springboot實現跨域

為了實現內網穿透,使用的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中的值主要有協議、域名、端口這幾種。請求如下:

瀏覽器第一次自動請求

緊接著本地的第二次請求也被服務器通過了:

服務器允許了本地的POST請求

可以看到,服務器響應了數據:

第二次請求成功

參考網址:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容