.Net Core微服務入門全紀錄(七)——IdentityServer4-授權認證

xhznl發表於2020-07-06

前言

上一篇【.Net Core微服務入門全紀錄(六)——EventBus-事件匯流排】中使用CAP完成了一個簡單的Eventbus,實現了服務之間的解耦和非同步呼叫,並且做到資料的最終一致性。這一篇將使用IdentityServer4來搭建一個鑑權中心,來完成授權認證相關的功能。

IdentityServer4官方文件:https://identityserver4.readthedocs.io/

鑑權中心

建立ids4專案

關於IdentityServer4的基本介紹和模板安裝可以看一下我的另一篇部落格【IdentityServer4 4.x版本 配置Scope的正確姿勢】,下面直接從建立專案開始。

來到我的專案目錄下執行:dotnet new is4inmem --name IDS4.AuthCenter

image-20200629210341489

執行完成後會生成以下檔案:

image-20200629210446718

用vs2019開啟之前的解決方案,把剛剛建立的ids專案新增進來:

image-20200629210933318

將此專案設為啟動項,先執行看一下效果:

image-20200629211848802

image-20200629212102283

專案正常執行,下面需要結合我們的業務稍微修改一下預設程式碼。

鑑權中心配置

修改Startup的ConfigureServices方法:

// in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);

Config類:

public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };

    public static IEnumerable<ApiResource> ApiResources =>
        new ApiResource[]
        {
            new ApiResource("orderApi","訂單服務")
            {
                ApiSecrets ={ new Secret("orderApi secret".Sha256()) },
                Scopes = { "orderApiScope" }
            },
            new ApiResource("productApi","產品服務")
            {
                ApiSecrets ={ new Secret("productApi secret".Sha256()) },
                Scopes = { "productApiScope" }
            }
        };

    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[]
        {
            new ApiScope("orderApiScope"),
            new ApiScope("productApiScope"),
        };

    public static IEnumerable<Client> Clients =>
        new Client[]
        {
            new Client
            {
                ClientId = "web client",
                ClientName = "Web Client",

                AllowedGrantTypes = GrantTypes.Code,
                ClientSecrets = { new Secret("web client secret".Sha256()) },

                RedirectUris = { "http://localhost:5000/signin-oidc" },
                FrontChannelLogoutUri = "http://localhost:5000/signout-oidc",
                PostLogoutRedirectUris = { "http://localhost:5000/signout-callback-oidc" },

                AllowedScopes = new [] {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "orderApiScope", "productApiScope"
                },
                AllowAccessTokensViaBrowser = true,

                RequireConsent = true,//是否顯示同意介面
                AllowRememberConsent = false,//是否記住同意選項
            }
        };
}

Config中定義了2個api資源:orderApi,productApi。2個Scope:orderApiScope,productApiScope。1個客戶端:web client,使用Code授權碼模式,擁有openid,profile,orderApiScope,productApiScope 4個scope。

TestUsers類:

public class TestUsers
{
    public static List<TestUser> Users
    {
        get
        {
            var address = new
            {
                street_address = "One Hacker Way",
                locality = "Heidelberg",
                postal_code = 69118,
                country = "Germany"
            };
            
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "818727",
                    Username = "alice",
                    Password = "alice",
                    Claims =
                    {
                        new Claim(JwtClaimTypes.Name, "Alice Smith"),
                        new Claim(JwtClaimTypes.GivenName, "Alice"),
                        new Claim(JwtClaimTypes.FamilyName, "Smith"),
                        new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                        new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
                    }
                },
                new TestUser
                {
                    SubjectId = "88421113",
                    Username = "bob",
                    Password = "bob",
                    Claims =
                    {
                        new Claim(JwtClaimTypes.Name, "Bob Smith"),
                        new Claim(JwtClaimTypes.GivenName, "Bob"),
                        new Claim(JwtClaimTypes.FamilyName, "Smith"),
                        new Claim(JwtClaimTypes.Email, "BobSmith@email.com"),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                        new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
                    }
                }
            };
        }
    }
}

TestUsers沒有做修改,用專案模板預設生成的就行。這裡定義了2個使用者alice,bob,密碼與使用者名稱相同。

至此,鑑權中心的程式碼修改就差不多了。這個專案也不放docker了,直接用vs來啟動,讓他執行在9080埠。/Properties/launchSettings.json修改一下:"applicationUrl": "http://localhost:9080"

Ocelot整合ids4

Ocelot保護api資源

鑑權中心搭建完成,下面整合到之前的Ocelot.APIGateway閘道器專案中。

首先NuGet安裝IdentityServer4.AccessTokenValidation

image-20200706100658900

修改Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication("orderService", options =>
        {
            options.Authority = "http://localhost:9080";//鑑權中心地址
            options.ApiName = "orderApi";
            options.SupportedTokens = SupportedTokens.Both;
            options.ApiSecret = "orderApi secret";
            options.RequireHttpsMetadata = false;
        })
        .AddIdentityServerAuthentication("productService", options =>
        {
            options.Authority = "http://localhost:9080";//鑑權中心地址
            options.ApiName = "productApi";
            options.SupportedTokens = SupportedTokens.Both;
            options.ApiSecret = "productApi secret";
            options.RequireHttpsMetadata = false;
        });

    //新增ocelot服務
    services.AddOcelot()
        //新增consul支援
        .AddConsul()
        //新增快取
        .AddCacheManager(x =>
        {
            x.WithDictionaryHandle();
        })
        //新增Polly
        .AddPolly();
}

修改ocelot.json配置檔案:

{
  "DownstreamPathTemplate": "/products",
  "DownstreamScheme": "http",
  "UpstreamPathTemplate": "/products",
  "UpstreamHttpMethod": [ "Get" ],
  "ServiceName": "ProductService",
  ......
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "productService",
    "AllowScopes": []
  }
},
{
  "DownstreamPathTemplate": "/orders",
  "DownstreamScheme": "http",
  "UpstreamPathTemplate": "/orders",
  "UpstreamHttpMethod": [ "Get" ],
  "ServiceName": "OrderService",
  ......
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "orderService",
    "AllowScopes": []
  }
}

新增了AuthenticationOptions節點,AuthenticationProviderKey對應的是上面Startup中的定義。

Ocelot代理ids4

既然閘道器是客戶端訪問api的統一入口,那麼同樣可以作為鑑權中心的入口。使用Ocelot來做代理,這樣客戶端也無需知道鑑權中心的地址,同樣修改ocelot.json:

{
  "DownstreamPathTemplate": "/{url}",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 9080
    }
  ],
  "UpstreamPathTemplate": "/auth/{url}",
  "UpstreamHttpMethod": [
    "Get",
    "Post"
  ],
  "LoadBalancerOptions": {
    "Type": "RoundRobin"
  }
}

新增一個鑑權中心的路由,實際中鑑權中心也可以部署多個例項,也可以整合Consul服務發現,實現方式跟前面章節講的差不多,這裡就不再贅述。

讓閘道器服務執行在9070埠,/Properties/launchSettings.json修改一下:"applicationUrl": "http://localhost:9070"

客戶端整合

首先NuGet安裝Microsoft.AspNetCore.Authentication.OpenIdConnect

image-20200706121544645

修改Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.Authority = "http://localhost:9070/auth";//通過閘道器訪問鑑權中心
            //options.Authority = "http://localhost:9080";

            options.ClientId = "web client";
            options.ClientSecret = "web client secret";
            options.ResponseType = "code";

            options.RequireHttpsMetadata = false;

            options.SaveTokens = true;

            options.Scope.Add("orderApiScope");
            options.Scope.Add("productApiScope");
        });

    services.AddControllersWithViews();
    
    //注入IServiceHelper
    //services.AddSingleton<IServiceHelper, ServiceHelper>();
    
    //注入IServiceHelper
    services.AddSingleton<IServiceHelper, GatewayServiceHelper>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceHelper serviceHelper)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    //程式啟動時 獲取服務列表
    //serviceHelper.GetServices();
}

修改/Helper/IServiceHelper,方法定義增加accessToken引數:

/// <summary>
/// 獲取產品資料
/// </summary>
/// <param name="accessToken"></param>
/// <returns></returns>
Task<string> GetProduct(string accessToken);

/// <summary>
/// 獲取訂單資料
/// </summary>
/// <param name="accessToken"></param>
/// <returns></returns>
Task<string> GetOrder(string accessToken);

修改/Helper/GatewayServiceHelper,訪問介面時增加Authorization引數,傳入accessToken:

public async Task<string> GetOrder(string accessToken)
{
    var Client = new RestClient("http://localhost:9070");
    var request = new RestRequest("/orders", Method.GET);
    request.AddHeader("Authorization", "Bearer " + accessToken);

    var response = await Client.ExecuteAsync(request);
    if (response.StatusCode != HttpStatusCode.OK)
    {
        return response.StatusCode + " " + response.Content;
    }
    return response.Content;
}

public async Task<string> GetProduct(string accessToken)
{
    var Client = new RestClient("http://localhost:9070");
    var request = new RestRequest("/products", Method.GET);
    request.AddHeader("Authorization", "Bearer " + accessToken);

    var response = await Client.ExecuteAsync(request);
    if (response.StatusCode != HttpStatusCode.OK)
    {
        return response.StatusCode + " " + response.Content;
    }
    return response.Content;
}

最後是/Controllers/HomeController的修改。新增Authorize標記:

[Authorize]
public class HomeController : Controller

修改Index action,獲取accessToken並傳入:

public async Task<IActionResult> Index()
{
    var accessToken = await HttpContext.GetTokenAsync("access_token");

    ViewBag.OrderData = await _serviceHelper.GetOrder(accessToken);
    ViewBag.ProductData = await _serviceHelper.GetProduct(accessToken);

    return View();
}

至此,客戶端整合也已完成。

測試

為了方便,鑑權中心、閘道器、web客戶端這3個專案都使用vs來啟動,他們的埠分別是9080,9070,5000。之前的OrderAPI和ProductAPI還是在docker中不變。

為了讓vs能同時啟動多個專案,需要設定一下,解決方案右鍵屬性:

image-20200706123144511

Ctor+F5啟動專案。

3個專案都啟動完成後,瀏覽器訪問web客戶端:http://localhost:5000/

image-20200706124027549

因為我還沒登入,所以請求直接被重定向到了鑑權中心的登入介面。使用alice/alice這個賬戶登入系統。

image-20200706124523974

登入成功後,進入授權同意介面,你可以同意或者拒絕,還可以選擇勾選scope許可權。點選Yes,Allow按鈕同意授權:

image-20200706124924213

同意授權後,就能正常訪問客戶端介面了。下面測試一下部分授權,這裡沒做登出功能,只能手動清理一下瀏覽器Cookie,ids4登出功能也很簡單,可以自行百度。

image-20200706125257382

清除Cookie後,重新整理頁面又會轉到ids4的登入介面,這次使用bob/bob登入:

image-20200706125759968

這次只勾選orderApiScope,點選Yes,Allow:

image-20200706130140730

這次客戶端就只能訪問訂單服務了。當然也可以在鑑權中心去限制客戶端的api許可權,也可以在閘道器層面ocelot.json中限制,相信你已經知道該怎麼做了。

總結

本文主要完成了IdentityServer4鑑權中心、Ocelot閘道器、web客戶端之間的整合,實現了系統的統一授權認證。授權認證是幾乎每個系統必備的功能,而IdentityServer4是.Net Core下優秀的授權認證方案。再次推薦一下B站@solenovex 楊老師的視訊,地址:https://www.bilibili.com/video/BV16b411k7yM ,雖然視訊有點老了,但還是非常受用。

需要程式碼的點這裡:https://github.com/xiajingren/NetCoreMicroserviceDemo

相關文章