使用MVC5 GoogleAuthenticationOptions在身份验证期间获取额外的用户配置文件信息

时间:2014-01-23 04:17:25

标签: asp.net-mvc authentication asp.net-mvc-5

当他或她使用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);

声明变量包含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: ben@sillypenguin.net }

任何人都可以帮助指出我做错了什么或我错过了什么来获取我正在寻找的额外个人资料?

1 个答案:

答案 0 :(得分:4)

如果简而言之,您必须使用OAuth 2.0与Google集成,而不是默认启用的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