.NET Core IdentityServer4實戰 第二章-OpenID Connect添加用戶認證


內容:本文帶大家使用IdentityServer4進行使用OpenID Connect添加用戶認證

作者:zara(張子浩) 歡迎分享,但需在文章鮮明處留下原文地址。

  在這一篇文章中我們希望使用OpenID Connect這種方式來驗證我們的MVC程序,我們首先需要干什么呢?那就是搞一個UI,這樣非常美觀既可以看到我們的身份驗證效果,那么IdentityServer官方已經給我們提供了一套UI了,我們從哪里可以獲取呢?

  可以通過這個地址就行克隆安裝到本地並附加到你的MVC程序中,地址。當然我們可以根據PowerShell 進行遠程拉取(以下命令在項目根目錄進行Code)

在Windows中我們的命令如下:

iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/master/getmaster.ps1'))

或者在macOS或Linux上使用bash one-line:

\curl -L https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/master/getmaster.sh | bash

 下圖所示是我在Windows Powershell中進行遠程拉取的。

安裝完項目中會添加一個Quickstart的這么一個文件夾,其中有IdentityServer給我們寫好的代碼,有控制器,模型,視圖,靜態文件等等。

當然還需要在Startup類中配置好你的MVC,這需要在ConfigureService里面將MVC添加到DI中並在Configure方法中將MVC中間件添加到管道上。

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })  .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "mvc";
                    options.SaveTokens = true;
                });
        }

  首先我們通過 AddAuthentication 將身份驗證服務添加到我們的DI中。其中參數有三個,第一個 DefaultScheme 它呢可以設置我們通過Cookies進行保存登錄信息。那么后面是我們的 DefaultChallengeScheme ,它的參數是 oidc ,也就是因為當我們需要用戶登錄時,我們將使用OpenID Connect協議。然后 AddCookie 我們使用添加可處理cookie的處理程序。最后, AddOpenIdConnect 用於配置執行OpenID Connect協議的處理程序。這 Authority 表明我們信任IdentityServer。然后我們通過 ClientId 識別這個客戶。  SaveTokens 用於在cookie中保留來自IdentityServer的令牌,同時我還關閉了JWT聲明映射,這樣會讓我們的應用程序流暢地通過: JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 。

  最后,我們需要讓我們的認證請求達到響應,應在管道中的MVC之前添加認證中間件。

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ///xxx//添加服務請求
            app.UseAuthentication();
       ///xxx
        }

  為了觸發驗證,我們在 HomeController 中添加一個特性 [Authorize] 。還要修改該Action的View以顯示用戶的信息,例如:

@using Microsoft.AspNetCore.Authentication
<dl> @foreach (var claim in User.Claims) { <dt>@claim.Type</dt> <dd>@claim.Value</dd> } </dl> <h2>Properties</h2> <dl> @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items) { <dt>@prop.Key</dt> <dd>@prop.Value</dd> } </dl>

如果你現在啟動的話,會出現內部錯誤,因為MVC客戶端在認證平台服務器中並沒有注冊。

現在我們回到我們的認證服務中心,在Config.cs中添加如下代碼(范圍代表您想要保護的內容以及客戶想要訪問的內容。與OAuth相比,OIDC中的范圍不代表API,而是代表用戶ID,名稱或電子郵件地址等身份數據。

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

然后,您需要將這些身份資源添加到Startup.cs中的IdentityServer配置中。使用 AddInMemoryIdentityResources 擴展方法調用 AddIdentityServer() 。

public void ConfigureServices(IServiceCollection services)
        {
            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetSoluction())
                .AddInMemoryClients(Config.GetClients())
                //.AddTestUsers(Config.GetUsers());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

   最后一步是將MVC客戶端的配置添加到IdentityServer。基於OpenID Connect的客戶端與我們目前添加的OAuth 2.0客戶端非常相似。但由於OIDC中的流程始終是交互式的,因此我們需要在配置中添加一些重定向URL。將以下內容添加到您的客戶端配置:

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        // other clients omitted...

        // OpenID Connect implicit flow client (MVC)
        new Client
        {
            ClientId = "mvc",
            ClientName = "MVC Client",
            AllowedGrantTypes = GrantTypes.Implicit,

            // where to redirect to after login
            RedirectUris = { "http://localhost:5002/signin-oidc" },

            // where to redirect to after logout
            PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile
            }
        }
    };
}

 就這樣我們啟動項目,現在啟動項目也就沒有什么問題了。

 其中我們用到了IdentityServer的Quickstart,雖說已經寫好了很多相關的控制器等等,這個Ui但是還是自己寫個好,或者改造!

總結:這篇文章說明了Server和Client之間的配置關系,Client不用管Server,只需要知道 Authority 的地址,攜帶其中的 ClientId ,而Server中相比上一篇文章中我們多了 Client 里面有ClientId用於和Client端匹配,那么我們就可以存到數據庫中!而Server端需要注入Client信息,通過 AddInMemoryClients 方法。當然你想到這里了,那么就一定可以介入QQ登錄、微信登錄了、后續的文章會寫這些!

 


免責聲明!

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



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