添加對外部認證的支持
接下來我們將添加對外部認證的支持。這非常簡單,因為你真正需要的是一個兼容ASP.NET Core的認證處理程序。
ASP.NET Core本身也支持Google,Facebook,Twitter,Microsoft帳戶和OpenID Connect。此外,你可以找到很多其他的認證供應商實現在這里。
cookies的作用
外部認證處理程序上的一個選項稱為SignInScheme,例如:
services.AddAuthentication() .AddGoogle("Google", options => { options.SignInScheme = "scheme of cookie handler to use"; options.ClientId = "..."; options.ClientSecret = "..."; })
登錄方案指定將暫時存儲外部認證的結果的cookie處理程序的名稱,例如 由外部提供商發送的身份單元。 這是必要的,因為在完成外部認證過程之前,通常會有幾個重定向。
鑒於這是一種常見的做法,IdentityServer專門為此外部提供程序工作流程注冊一個Cookie處理程序。 該方案通過IdentityServerConstants.ExternalCookieAuthenticationScheme
常量表示。 如果您要使用我們的外部cookie處理程序,那么對於上面的SignInScheme
,您將分配的值為IdentityServerConstants.ExternalCookieAuthenticationScheme
常量:
services.AddAuthentication() .AddGoogle("Google", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.ClientId = "..."; options.ClientSecret = "..."; })
您也可以注冊您自己的自定義Cookie處理程序,如下所示:
services.AddAuthentication() .AddCookie("YourCustomScheme") .AddGoogle("Google", options => { options.SignInScheme = "YourCustomScheme"; options.ClientId = "..."; options.ClientSecret = "..."; })
對於特定的場景,您還可以將外部Cookie機制短路,並將外部用戶直接轉發到主要Cookie處理程序。 這通常涉及在外部處理程序上處理事件,以確保從外部身份源執行正確的聲明轉換。
添加Google支持
為了能夠使用Google進行身份驗證,您首先需要向他們進行注冊。這是在他們的開發者控制台完成的。創建一個新項目,啟用Google+ API,並通過將/signin-google路徑添加到您的基地址(例如http//localhost:5000/signin-google)來配置本地IdentityServer
的回撥地址。
如果您在端口5000上運行 - 您可以簡單地使用下面的代碼片段中的客戶端ID /密碼,因為這是由我們預先注冊的。
首先添加Google身份驗證處理程序到DI。這是通過添加這個片段來ConfigureServices
完成的Startup
:
public void ConfigureServices(IServiceCollection services) { // 使用內存存儲,密鑰,客戶端和資源來配置身份服務器。 services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(Config.GetApiResources())//添加api資源 .AddInMemoryClients(Config.GetClients())//添加客戶端 .AddTestUsers(Config.GetUsers()) //添加測試用戶 .AddInMemoryIdentityResources(Config.GetIdentityResources());//添加對OpenID Connect的支持 //注冊mvc服務 services.AddMvc(); //添加Google登錄 services.AddAuthentication() .AddGoogle("Google", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.ClientId = "434483408261-55tc8n0cs4ff1fe21ea8df2o443v2iuc.apps.googleusercontent.com"; options.ClientSecret = "3gcoTrEDPPJ0ukn_aYYT6PWo"; }); }
默認情況下,IdentityServer
專門為外部身份驗證的結果配置cookie處理程序(基於常量的方案IdentityServerConstants.ExternalCookieAuthenticationScheme
)。Google處理程序的配置然后使用該cookie處理程序。為了更好地理解如何完成,請參閱快速入門文件夾AccountController
下的類。
現在運行訪問http://localhost:5000/account/login
- 您將在登錄頁面上看到一個Google按鈕:
登錄認證之后,您可以看到,這些聲明現在來自Google數據。這里需要翻、牆,不然獲取不到Google賬號信息。