1. 程式人生 > >NetCore專案實戰篇05---新增Ocelot閘道器並整合identity server4認證

NetCore專案實戰篇05---新增Ocelot閘道器並整合identity server4認證

       今天來給我們的專案增加API閘道器,使用Ocelot。 它是系統暴露在外部的一個訪問入口,這個有點像代理訪問的傢伙,就像一個公司的門衛承擔著定址、限制進入、安全檢查、位置引導、等等功能。同時我們還要在閘道器中集成了Identity Server(Identity Server在專案中的使用見上一篇文章),當閘道器需要請求認證資訊的時候會與Identity Server伺服器進行互動來完成。多說也無益,直接上專案吧。

  1. 新建一個空的.netcore專案,命名為Zhengwei.Gateway新建好後引入Ocelot包,我們之前專案中已有Zhengwei.Identity和Zhengwei.Use.Api,專案結構圖如下:

     

  2. 在上圖中我們看到一個Ocelot.json檔案,裡面設定了所有對當前這個閘道器的配置。它會接收所有的客戶端請求,並路由到對應的下游伺服器進行處理,再將請求結果返回。而這個上下游請求的對應關係也被稱之為路由。配置如下:

       

{
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost"
  },
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/users",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "33545"
        }
      ],
      "UpstreamPathTemplate": "/users",
      "UpstreamHttpMethod": [ "Get" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "zhengwei",
        "AllowedScopes": []
      }
    },
    {
      "DownstreamPathTemplate": "/connect/token",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "1110"
        }
      ],
      "UpstreamPathTemplate": "/connect/token",
      "UpstreamHttpMethod": [ "Post" ]

    }

  ]

}

       其中,DownstreamPathTemplate是下游服務。DownstreamScheme是下游服務http schema。DownstreamHostAndPorts是下游服務的地址,如果使用LoadBalancer的話這裡可以填多項。UpstreamPathTemplate: 上游也就是使用者輸入的請求Url模板。UpstreamHttpMethod: 上游請求http方法,可使用陣列

       從配置檔案中我們可以看出本來通過http://localhost:33545/api/users訪問的use api現在可以通過http://localhost: 4157/api/users來訪問,本來通過http://localhost: 1110/connect/token來訪問的現在可以通過http://localhost: 4157/connect/token來訪問,http://localhost: 4157是閘道器專案的地址。

      3、在專案啟動時來引入我們的配置檔案Ocelot.json吧,寫在Program.cs檔案中,程式碼如下:

public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((webhost,builder)=>{
                    builder.SetBasePath(webhost.HostingEnvironment.ContentRootPath)
                           .AddJsonFile("Ocelot.json");
        })
                .UseStartup<Startup>()
                .UseUrls("http://+:80")
                .Build();
    }

  4、 在Startup.cs檔案中加入我們的認證服務吧,注意這裡的authenticationProviderKey=“zhengwei”,要與我們Ocelot.json檔案中的"AuthenticationProviderKey": "zhengwei"一致,程式碼如下:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var authenticationProviderKey = "zhengwei";
    
            services.AddAuthentication()
                .AddIdentityServerAuthentication(authenticationProviderKey, options=> {
                    options.Authority = "http://localhost:1110/";
                    options.ApiName = "gateway_api";
                    options.SupportedTokens = SupportedTokens.Both;
                    options.ApiSecret = "secret";
                    options.RequireHttpsMetadata = false;
                });
            services.AddOcelot();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseOcelot();
        }
    }

5、一切就序,那我們就開始測試吧,右鍵解決方案---》屬性-->多個專案啟動----》操作中將三個專案都設定為啟動,關閉後點擊啟動,啟動好後,開啟postman,輸入網址http://localhost:4157/users

 

 可惜,給我們返回的驗證嗎是401未認證,然來是我們沒有提交對應的token.那就先獲取token值吧。輸入網址:http://localhost:4157/connect/token,得到如下的返回值,其中access_token就是我們要的token值,複製下來吧。

 

 

6、複製下我們的token後,再次請求http://localhost:4157/users前要加入引數,在Headers中輸入key:   Authorization   輸入對應的值:bearer  + 複製過來的access_token,再次請求,會獲取到useapi介面正常返回的值了。如下圖

 

 至此,我們的ocelot和Identity Server在我們的專案中整合完畢。&n