当用户使用 Google 帐户登录我的 MVC5 网站时,我尝试获取用户的出生日期和头像/图标/照片/图片。
我读过这篇文章:
Get ExtraData from MVC5 framework OAuth/OWin identity provider with external auth provider
但这没有多大意义……我应该知道这一点吗?
在我的 Startup.Auth.cs 文件中,我有以下代码片段:
var gProvider = new GoogleAuthenticationProvider { OnAuthenticated = context => { var claims = context.Identity.Claims.ToList(); return Task.FromResult(0); } };
var gOptions = new GoogleAuthenticationOptions { Provider = gProvider };
app.UseGoogleAuthentication(gOptions);
claims 变量包含 5 个项目:(每个项目以“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/ ”开头)
0: { nameidentifier: https://www.google.com/accounts/.../id?id... }
1: { givenname: Benjamin }
2: { surname: Day }
3: { name: Benjamin Day }
4: { emailaddress: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b4b3b896a5bfbabaafa6b3b8b1a3bfb8f8b8b3a2" rel="noreferrer noopener nofollow">[email protected]</a> }
任何人都可以帮助指出我做错了什么或我缺少什么来获取我正在寻找的额外个人资料数据吗?
最佳答案
简而言之,您必须使用与 Google 集成的 OAuth 2.0,而不是默认启用的 Open ID。
public class CustomGoogleProvider : GoogleOAuth2AuthenticationProvider
{
public override Task Authenticated(GoogleOAuth2AuthenticatedContext context)
{
context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString()));
context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString()));
return base.Authenticated(context);
}
}
并将其用作
var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "{{Your Client Id}}",
ClientSecret = "{{Your Client Secret}}",
CallbackPath = new PathString("/Account/ExternalGoogleLoginCallback"),
Provider = new CustomGoogleProvider(),
};
googleOAuth2AuthenticationOptions.Scope.Add("email");
app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions);
我详细描述了这个过程here
关于asp.net-mvc - 使用 MVC 5 Google AuthenticationOptions 在身份验证过程中获取额外的用户个人资料信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21299251/