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

来源:https://www.cnblogs.com/xhznl/archive/2020/07/06/13132260.html
-Advertisement-
Play Games

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


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

前言

上一篇【.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, "[email protected]"),
                        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, "[email protected]"),
                        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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 通過小程式登錄獲取小程式openID <button hidden="{{is_login}}" class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo" ...
  • 公眾號和小程式綁定微信開放平臺 微信開放平臺需要認證(300) 然後進行相關的綁定,綁定時需要相關賬號的原始管理者進行掃碼綁定 小程式也是一樣操作 小程式獲取unionID <button hidden="{{is_login}}" class='bottom' type='primary' ope ...
  • 前言 發年終獎這件事,在互聯網公司正在成為一種傳統,就像不加班都不好意思說是搞互聯網的一樣。 年終獎其實是一件非常有儀式感的事情:年末拿錢回家過年。 今天,和大家看一下那些互聯網行業被大家津津樂道且羡慕嫉妒的年終獎們,同時也期待一下今年的年終獎(嘿嘿嘿 看看阿裡、位元組跳動、華為等這些大廠的年終獎都發 ...
  • 我們一般創建的線程都是普通非守護線程,守護線程是為普通線程服務的。這個說法比較抽象。 具體一個很大的區別是: JVM中所有的線程都是守護線程的時候,JVM就可以退出了--JVM不會等待守護線程是否運行結束 如果還有一個或以上的非守護線程則不會退出 非守護線程例子 public static void ...
  • 一直想深入go語言,下定決心今年要狠抓go語言 | 文章名稱 | 文章鏈接 | | | | | Golang網路編程 | https://www.cnblogs.com/ZhuChangwu/p/13198872.html | | | | | | | ...
  • 一、實現Runnable介面 public class RunnableDemo implements Runnable { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.print ...
  • 從今天起,我將製作一個電影推薦項目,在此寫下博客,記錄每天的成果。 其實,從我發佈 C# 爬取貓眼電影數據 這篇博客後, 我就已經開始製作電影推薦項目了,今天寫下這篇博客,也是因為項目進度已經完成50%了,我就想在這一階段停一下,回顧之前學到的知識。 一、主要為手機端 考慮到項目要有實用性,我選擇了 ...
  • using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System. ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...