CORS解決跨域問題(403問題)

一、什麼是跨域問題?web

  跨域問題是瀏覽器對於ajax請求的一種安全限制:一個頁面發起的ajax請求,只能是用當前頁同域名同端口的路徑,這能有效的阻止跨站攻擊。ajax

 

二、跨域問題出現的條件:spring

  一、跨域問題是ajax請求特有的問題。後端

     二、先後端的域名、端口不一致。跨域

三、CORS跨域解決原理簡單分析:瀏覽器

  CORS須要瀏覽器和服務器的同時支持。安全

 

  瀏覽器端(瀏覽器自動完成):服務器

    發送兩次請求,第一次發送option請求 --詢問服務器端是否能夠跨域;cookie

    第二次才發送正式請求。cors

 

  服務器端:

    經過攔截器/過濾器統一實現,過濾器過濾全部的請求,匹配對應的ip+端口,若是符合條件,則在響應頭中添加容許跨域訪問的信息

四、CORS跨域解決方案:

  一、  在網關中配置一個CORS的跨域過濾器:SpringMVC已經幫咱們寫好了CORS的跨域過濾器,直接使用便可。

  二、  在網關中建立一個配置文件告訴過濾器容許經過的域名和端口便可。

 

  在網關中添加以下配置文件便可(springMVC環境下)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1) 容許經過的域,不要寫*,不然cookie就沒法使用了
        config.addAllowedOrigin("http://127.0.0.1:7001");
        config.addAllowedOrigin("http://localhost:7001");
        //2) 是否發送Cookie信息
        config.setAllowCredentials(true);
        //3) 容許的請求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        // 4)容許的頭信息
        config.addAllowedHeader("*");
        //2.添加映射路徑,咱們攔截一切請求
        UrlBasedCorsConfigurationSource configSource = new
                UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}
相關文章
相關標籤/搜索