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

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

Intro

咱們在使用先後端分離的模式進行開發的時候,若是前端項目和api項目不是一個域名下每每會有跨域問題。今天來介紹一下咱們在Ocelot網關配置的跨域。javascript

什麼是跨域

跨域:css

瀏覽器對於javascript的同源策略的限制,例如a.cn下面的js不能調用b.cn中的js,對象或數據(由於a.cn和b.cn是不一樣域),因此跨域就出現了.html

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

同源策略:java

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

好比:我在本地上的域名是study.cn,請求另一個域名一段數據jquery

image

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

image

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

study.cn/json/jsonp/jsonp.htmlgithub

當協議、子域名、主域名、端口號中任意一個不相同時,都算做不一樣域。不一樣域之間相互請求資源,就算做「跨域」。

請求地址 形式 結果
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

相關文章
相關標籤/搜索