1. 程式人生 > >常見跨域解決方案以及Ocelot 跨域配置

常見跨域解決方案以及Ocelot 跨域配置

常見跨域解決方案以及Ocelot 跨域配置

Intro

我們在使用前後端分離的模式進行開發的時候,如果前端專案和api專案不是一個域名下往往會有跨域問題。今天來介紹一下我們在Ocelot閘道器配置的跨域。

什麼是跨域

跨域:

瀏覽器對於javascript的同源策略的限制,例如a.cn下面的js不能呼叫b.cn中的js,物件或資料(因為a.cn和b.cn是不同域),所以跨域就出現了.

上面提到的,同域的概念又是什麼呢??? 簡單的解釋就是相同域名,埠相同,協議相同

同源策略:

請求的url地址,必須與瀏覽器上的url地址處於同域上,也就是域名,埠,協議相同.

比如:我在本地上的域名是study.cn,請求另外一個域名一段資料

這個時候在瀏覽器上會報錯:

這個就是同源策略的保護,如果瀏覽器對javascript沒有同源策略的保護,那麼一些重要的機密網站將會很危險~

study.cn/json/jsonp/jsonp.html

當協議、子域名、主域名、埠號中任意一個不相同時,都算作不同域。不同域之間相互請求資源,就算作“跨域”。

請求地址 形式 結果
http://study.cn/test/a.html 同一域名,不同資料夾 成功
http://study.cn/json/jsonp/jsonp.html 同一域名,統一資料夾 成功
http://a.study.cn/json/jsonp/jsonp.html 不同域名,檔案路徑相同 失敗
http://study.cn:8080/json/jsonp/jsonp.html 同一域名,不同埠 失敗
https://study.cn/json/jsonp/jsonp.html 同一域名,不同協議  失敗

跨域幾種常見的解決方案

解決跨域問題有幾種常見的解決方案:

跨域資源共享(CORS)

通過在伺服器端配置 CORS 策略即可,每門語言可能有不同的配置方式,但是從本質上來說,最終都是在需要配置跨域的資源的Response上增加允許跨域的響應頭,以實現瀏覽器跨域資源訪問,詳細可以參考MDN上的這篇CORS介紹

JSONP

JSONP 方式實際上返回的是一個callbak,通常為了減輕web伺服器的負載,我們把js、css,img等靜態資源分離到另一臺獨立域名的伺服器上,在html頁面中再通過相應的標籤從不同域名下載入靜態資源,而被瀏覽器允許,基於此原理,我們可以通過動態建立script,再請求一個帶參網址實現跨域通訊。

  1. 原生實現:
 <script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // 傳參一個回撥函式名給後端,方便後端返回時執行這個在前端定義的回撥函式
    script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
    document.head.appendChild(script);

    // 回撥執行函式
    function handleCallback(res) {
        alert(JSON.stringify(res));
    }
 </script>

服務端返回如下(返回時即執行全域性函式):

handleCallback({"status": true, "user": "admin"})
  1. jquery ajax:
$.ajax({
    url: 'http://www.domain2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 請求方式為jsonp
    jsonpCallback: "handleCallback",    // 自定義回撥函式名
    data: {}
});

後端 node.js 程式碼示例:

var querystring = require('querystring');
var http = require('http');
var server = http.createServer();

server.on('request', function(req, res) {
    var params = qs.parse(req.url.split('?')[1]);
    var fn = params.callback;

    // jsonp返回設定
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    res.write(fn + '(' + JSON.stringify(params) + ')');

    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080...');

JSONP 只支援 GET 請求

代理

  1. 前端代理

在現代化的前端開發的時候往往可以配置開發代理伺服器,實際作用相當於做了一個請求轉發,但實際請求的api地址是沒有跨域問題的,然後由實際請求的api伺服器轉發請求到實際的存在跨域問題的api地址。

angular 配置開發代理可以參考 angular反向代理配置

  1. 後端代理

後端可以通過一個反向代理如(nginx),統一暴露一個服務地址,然後為所有的請求設定跨域配置,配置 CORS 響應頭,Ocelot是ApiGateway,也可以算是api的反向代理,但不僅僅如此。

Ocelot 跨域配置

示例程式碼:

app.UseOcelot((ocelotBuilder, pipelineConfiguration) =>
                {
                    // This is registered to catch any global exceptions that are not handled
                    // It also sets the Request Id if anything is set globally
                    ocelotBuilder.UseExceptionHandlerMiddleware();
                    // Allow the user to respond with absolutely anything they want.
                    if (pipelineConfiguration.PreErrorResponderMiddleware != null)
                    {
                        ocelotBuilder.Use(pipelineConfiguration.PreErrorResponderMiddleware);
                    }
                    // This is registered first so it can catch any errors and issue an appropriate response
                    ocelotBuilder.UseResponderMiddleware();
                    ocelotBuilder.UseDownstreamRouteFinderMiddleware();
                    ocelotBuilder.UseDownstreamRequestInitialiser();
                    ocelotBuilder.UseRequestIdMiddleware();
                    ocelotBuilder.UseMiddleware<ClaimsToHeadersMiddleware>();
                    ocelotBuilder.UseLoadBalancingMiddleware();
                    ocelotBuilder.UseDownstreamUrlCreatorMiddleware();
                    ocelotBuilder.UseOutputCacheMiddleware();
                    ocelotBuilder.UseMiddleware<HttpRequesterMiddleware>();
                    // cors headers
                    ocelotBuilder.Use(async (context, next) =>
                    {
                        if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))
                        {
                            var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray<string>();
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowedOrigins.Length == 0 ? new[] { "*" } : allowedOrigins));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, new[] { "*" }));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, new[] { "*" }));
                        }
                        await next();
                    });
                })
                .Wait();

這裡擴充套件了一個 Ocelot pipeline 的配置,這樣我們可以直接很方便的直接在 Startup 裡配置 Ocelot 的請求管道。

核心程式碼:

// cors headers
                    ocelotBuilder.Use(async (context, next) =>
                    {
                        if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))
                        {
                            var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray<string>();
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowedOrigins.Length == 0 ? new[] { "*" } : allowedOrigins));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, new[] { "*" }));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, new[] { "*" }));
                        }
                        await next();
                    });

在 HttpRequester 中介軟體後面新增這個中介軟體在響應中增加跨域請求頭配置,這裡先判斷了一下下面的api有沒有配置,如果已經配置則不再配置,使用下游api的跨域配置,這樣一來,只需要在閘道器配置指定的允許跨域訪問的源即使下游api沒有設定跨域也是可以訪問了

需要說明一下的是如果想要這樣配置需要 Ocelot 13.2.0 以上的包,因為之前 HttpRequester 這個中介軟體沒有呼叫下一個中介軟體,詳見 https://github.com/ThreeMammals/Ocelot/pull/830

Reference

  • https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
  • https://segmentfault.com/a/1190000011145364
  • https://github.com/ThreeMammals/Ocelot/pull/830