第三方登录
除了自定义身份认证之外,Identity Server
也支持使用第三方登录。很多知名平台都提供了第三方登录,如 Google,Github,Microsoft,微信,微博等。下面我们以 Google 和 Github 为例简单演示第三方登录集成,其它第三方认证各平台申请方式略有差异,但集成方式基本相同。
1. Google
1.1 申请Google认证
使用第三方授权首先需要到对应平台下申请认证信息。Google 认证信息需要到Google Cloud Platform 控制台申请。
我们首先创建一个项目。
项目创建完成后,进入 API 和服务。
第一次使用时需要创建一个 OAuth 同意屏幕。
OAuth 同意屏幕创建过程不再逐步讲解,下图是其摘要信息。
接下来开始正式创建凭据。
Identity Server
是Web应用,所以下面我们选择创建 Web应用。
下面根据Identity Server
信息填写Web应用客户端信息。
客户端创建完成后得到下图的凭据。
1.2 集成Google认证
集成 Google 认证需要借助Microsoft.AspNetCore.Authentication.Google Nuget 包。
Identity Server
默认项目模板中已经集成了 Google 认证,我们只需要替换为刚申请的凭证信息即可。
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddAuthentication()
.AddGoogle(options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
// register your IdentityServer with Google at https://console.developers.google.com
// enable the Google+ API
// set the redirect URI to https://localhost:5000/signin-google
options.ClientId = "778213714307-cjpuh2td8uml33lke0n818t7ft37kfvb.apps.googleusercontent.com";
options.ClientSecret = "Eiv41aO7KHdq2BNSpXx5Vkzr";
});
}
1.3 客户端Google登录
这里我们使用 Implicit 中的客户端为例来演示 Google 认证过程。
在客户端登录被重定向到Identity Server
后我们可以看到 Google 认证的入口。
点击 Google 认证按钮被重定向到 Google 认证授权页面
认证通过后可以在客户端拿到 Google 的 Identity
数据如下图。
2. Github
2.1 申请Github认证
Github 认证信息需要到Settings / Developer settings申请。
在Developer settings
中创建 OAuth 应用。
应用创建完毕后可以得到凭证如下图。
2.2 集成Github认证
集成 Github 认证需要借助AspNet.Security.OAuth.GitHub Nuget 包。
Github 认证集成方式与 Google 基本一致,更多内容可以参考官方案例。
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddAuthentication()
.AddGitHub(options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ClientId = "49e302895d8b09ea5656";
options.ClientSecret = "98f1bf028608901e9df91d64ee61536fe562064b";
options.Scope.Add("user:email");
});
}
2.3 客户端Github登录
这里我们继续使用 Implicit 中的客户端为例来演示 Github 认证过程。
在客户端登录被重定向到Identity Server
后我们可以看到Google认证的入口。
点击 Github 认证按钮被重定向到 Github 认证授权页面。
认证通过后可以在客户端拿到 Github 的Identity
数据如下图。