第12章 添加对外部认证的支持 - Identity Server 4 中文文档(v1.0.0)

时间:2023-03-09 14:35:02
第12章 添加对外部认证的支持 - Identity Server 4 中文文档(v1.0.0)

注意

对于任何先决条件(例如模板),首先要查看概述。

接下来,我们将添加对外部认证的支持。这非常简单,因为您真正需要的是ASP.NET Core兼容的身份验证处理程序。

ASP.NET Core本身支持Google,Facebook,Twitter,Microsoft Account和OpenID Connect。此外,你可以找到很多其他的认证供应商实现在这里

12.1 添加Google支持

要使用Google进行身份验证,首先需要向他们注册。这是在他们的开发者控制台完成的。通过将/signin-google路径添加到您的基地址(例如http//localhost5000/signin-google),创建一个新项目,启用Google+ API并配置您本地IdentityServer的回调地址。

开发者控制台将向您显示由Google发布的客户端ID和密码 - 您将在下一步中使用该密码。

将Google身份验证处理程序添加到IdentityServer主机的DI中。这是通过添加该代码段完成StartupConfigureServices

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按钮:

在使用MVC客户端进行身份验证后,您可以看到声明现在来自Google数据。

12.2 进一步的实验

您可以添加其他外部提供程序。我们有一个云托管的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"
};
});

现在,用户应该能够使用云托管的演示标识提供程序。

注意

快速入门UI自动配置外部用户。当外部用户首次登录时,将创建新的本地用户,并且所有外部声明都将复制并与新用户关联。你处理这种情况的方式完全取决于你。也许你想首先展示某种注册UI。可以在此处找到默认快速入门的源代码。可以在此处找到执行自动配置的控制器。

github地址