ASP.NET Core的身份认证框架IdentityServer4--(4)添加第三方快捷登录

2022-11-16,,,,

添加对外部认证的支持

接下来我们将添加对外部认证的支持。这非常简单,因为你真正需要的是一个兼容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账号信息。

ASP.NET Core的身份认证框架IdentityServer4--(4)添加第三方快捷登录的相关教程结束。

《ASP.NET Core的身份认证框架IdentityServer4--(4)添加第三方快捷登录.doc》

下载本文的Word格式文档,以方便收藏与打印。