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在我們的項目中集成完畢。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM