.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
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...