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

內容:本文帶你們使用IdentityServer4進行使用OpenID Connect添加用戶認證git

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

  在這一篇文章中咱們但願使用OpenID Connect這種方式來驗證咱們的MVC程序,咱們首先須要幹什麼呢?那就是搞一個UI,這樣很是美觀既能夠看到咱們的身份驗證效果,那麼IdentityServer官方已經給咱們提供了一套UI了,咱們從哪裏能夠獲取呢?shell

  能夠經過這個地址就行克隆安裝到本地並附加到你的MVC程序中,地址。固然咱們能夠根據PowerShell 進行遠程拉取(如下命令在項目根目錄進行Code)數據庫

在Windows中咱們的命令以下:bash

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給咱們寫好的代碼,有控制器,模型,視圖,靜態文件等等。cookie

固然還須要在Startup類中配置好你的MVC,這須要在ConfigureService裏面將MVC添加到DI中並在Configure方法中將MVC中間件添加到管道上。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(); 。app

  最後,咱們須要讓咱們的認證請求達到響應,應在管道中的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登陸、微信登陸了、後續的文章會寫這些!

相關文章
相關標籤/搜索