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

Tips:本篇已加入系列文章閱讀目錄,可點擊查看更多相關文章。html

前言

上一篇【.Net Core微服務入門全紀錄(六)——EventBus-事件總線】中使用CAP完成了一個簡單的Eventbus,實現了服務之間的解耦和異步調用,而且作到數據的最終一致性。這一篇將使用IdentityServer4來搭建一個鑑權中心,來完成受權認證相關的功能。git

IdentityServer4官方文檔:https://identityserver4.readthedocs.io/github

鑑權中心

建立ids4項目

關於IdentityServer4的基本介紹和模板安裝能夠看一下個人另外一篇博客【IdentityServer4 4.x版本 配置Scope的正確姿式】,下面直接從建立項目開始。web

來到個人項目目錄下執行:dotnet new is4inmem --name IDS4.AuthCenterdocker

image-20200629210341489

執行完成後會生成如下文件:json

image-20200629210446718

用vs2019打開以前的解決方案,把剛剛建立的ids項目添加進來:api

image-20200629210933318

將此項目設爲啓動項,先運行看一下效果:瀏覽器

image-20200629211848802

image-20200629212102283

項目正常運行,下面須要結合咱們的業務稍微修改一下默認代碼。緩存

鑑權中心配置

修改Startup的ConfigureServices方法:app

// 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

相關文章
相關標籤/搜索