IdentityServer4 快速入門#4:添加外部身份驗證

Note

對于任何先決條件(例如模板),請先查看概述。

接下來,我們將添加對外部身份驗證的支持。 這真的很容易,因為您真正需要的只是一個與ASP.NET Core兼容的身份驗證處理程序。

ASP.NET Core本身附帶對Google,Facebook,Twitter,Microsoft帳戶和OpenID Connect的支持。 另外,您可以在此處找到許多其他身份驗證提供程序的實現。

添加Google支持

為了能夠使用Google進行身份驗證,您首先需要向他們注冊。 這是在其開發人員控制臺https://www.ecshop.cx/article-519.html完成的
的。 創建一個新項目,啟用Google+ API,并通過在基本地址中添加/signin-google路徑(例如http://localhost:5000/signin-google)來配置本地IdentityServer的回調地址。

開發者控制臺將向您顯示由Google發布的(ClientID)客戶端ID和(Secret)機密-下一步將需要使用該ID。
將Google身份驗證處理程序添加到IdentityServer主機的DI中。 這是通過將以下代碼段添加到Startup中的ConfigureServices來完成的:

services.AddAuthentication()
    .AddGoogle("Google", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

        options.ClientId = "<insert here>";
        options.ClientSecret = "<insert here>";
    });

默認情況下,IdentityServer專門為外部身份驗證的結果配置cookie處理程序(使用基于常量IdentityServerConstants.ExternalCookieAuthenticationScheme的方案)。 然后,Google處理程序的配置將使用該Cookie處理程序。

現在運行MVC客戶端并嘗試進行身份驗證-您將在登錄頁面上看到一個Google按鈕:

image.png

通過MVC客戶端進行身份驗證后,您可以看到聲明現在從Google數據中獲取。

進一步的實驗

您可以添加其他外部提供程序。 我們有IdentityServer4的云托管演示版,您可以使用OpenID Connect進行集成。
將OpenId Connect處理程序添加到DI:

services.AddAuthentication()
    .AddGoogle("Google", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

        options.ClientId = "<insert here>";
        options.ClientSecret = "<insert here>";
    })
    .AddOpenIdConnect("oidc", "OpenID Connect", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
        options.SignOutScheme = IdentityServerConstants.SignoutScheme;
        options.SaveTokens = true;

        options.Authority = "https://demo.identityserver.io/";
        options.ClientId = "implicit";

        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "role"
        };
    });

現在,用戶應該可以使用云托管的演示身份提供程序。

Note

快速入門UI自動設置外部用戶。 當外部用戶首次登錄時,將創建一個新的本地用戶,并且所有外部聲明將被復制并與該新用戶相關聯。 但是,如何處理這種情況完全取決于您自己。 也許您想先顯示某種注冊UI。 默認快速入門的源代碼可以在 這里找到。 可以在此處找到執行自動配置的控制器。

Source Code here

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容