she*_*rtu 3 c# asp.net authentication google-oauth asp.net-core
我想在 ASP .NET Core 中实现一个身份验证系统,其中:
用户单击一个看起来像标准 Google 登录按钮的按钮。
然后系统会提示用户登录 Google 帐户并登录。
阿http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier与值权利要求相等的user_id经签署的谷歌帐户添加到的User在可变RazorBasePage类。
服务器将用户添加到用户表中,user_id并将其作为主键。
我最初研究了使用内置 ASP .NET Identity 系统的解决方案。然而,我很快意识到它的功能远远超过我所需要的。
接下来,我按照这篇文章实现了一个系统,当用户尝试使用带有 [Authorize] 属性标记的控制器或操作时,必须使用他们的 Google 帐户进行身份验证。
同时,我还使用这篇文章研究了一个登录系统。本文实现了一个系统,开发人员可以在其中实现自己的自定义授权系统,例如检查硬编码密码。
而且我还调查了一些谷歌的开发者页面关于身份这个系统允许开发者在客户端轻松实现一个身份验证系统——需要额外的步骤来将身份验证传递给服务器。
这组图像应该有助于传达上述授权系统。我当前在 StartUp.cs 中的 ConfigureServices 方法包含以下代码:
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options => {
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.SaveTokens = true;
});
Run Code Online (Sandbox Code Playgroud)
任何关于如何实现这样一个系统的提示将不胜感激。谢谢!
看起来 Google 不赞成使用 Google+ 来检索用户信息:https : //github.com/aspnet/AspNetCore/issues/6486
在 ASP.Net Core MVC 2.0 中,我最终在 Startup.cs:ConfigureServices 中执行此操作
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options => {
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
options.SaveTokens = true;
options.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
options.ClaimActions.Clear();
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
options.ClaimActions.MapJsonKey("urn:google:profile", "link");
options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
options.ClaimActions.MapJsonKey("picture", "picture");
})
;
Run Code Online (Sandbox Code Playgroud)
不要忘记在 app.UseMvc() 之前添加以下行
app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)
此外,您还需要为您的应用程序配置 Google API 以进行云身份识别。
要显示信息,您可以执行以下操作:
@Context.User.Identity.Name
<img src="@Context.User.Claims.SingleOrDefault(c => c.Type == "picture")?.Value" />
Run Code Online (Sandbox Code Playgroud)
最后:请考虑此信息的隐私。存储私人信息而不告诉用户您正在存储它以及用于什么目的是不道德的(并且在大多数司法管辖区是不合法的)。