从MVC中的Google OAuth API检索出生日期

时间:2015-01-09 11:26:19

标签: c# asp.net-mvc oauth google-oauth owin

我添加了以下范围来访问用户的数据

#region Google
 var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = ConfigurationManager.AppSettings["Google_AppID"],
            ClientSecret = ConfigurationManager.AppSettings["Google_AppSecret"]
        };
        googleAuthenticationOptions.Scope.Add("profile");
        googleAuthenticationOptions.Scope.Add("email");
googleAuthenticationOptions.Provider = new GoogleOAuth2AuthenticationProvider()
        {
            OnAuthenticated = async context =>
            {
                //context.Identity.AddClaim(new Claim("birthday", context.User.GetValue("birthday").ToString()));
                string claimType;
                bool bAddClaim = false;
                foreach (var claim in context.User)
                {

                    claimType = string.Empty;
                    bAddClaim = false;
                    switch (claim.Key)
                    {
                        case "given_name":
                            claimType = "FirstName";
                            bAddClaim = true;
                            break;
                        case "family_name":
                            claimType = "LastName";
                            bAddClaim = true;
                            break;
                        case "gender":
                            claimType = "gender";
                            bAddClaim = true;
                            break;
                    }

                    if (bAddClaim)
                    {
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                    }
                }
            }
        };

通过放置断点,在侧面foreach循环中的 context.user 进行调试 我收到以下信息

{
"sub": "101111724115925537597",
"name": "Alok Nath",
"given_name": "Alok",
"family_name": "Nath",
"profile": "https://plus.google.com/101111724115925537597",
"picture":"https://lh3.googleusercontent.com/XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/
          photo.jpg",
"email": "aloknathbabuji786@gmail.com",
"email_verified": true,
"gender": "male",
"locale": "en"
}

因此,即使添加了“个人资料”范围,我也不会将生日作为返回值的一部分。我确保该配置文件将生日可见性设置为公开,即所有人都可以看到。为了从 Google 检索生日,我需要做哪些具体的范围或具体设置?

或者有什么方法可以解决这个问题,请发布解决方案

1 个答案:

答案 0 :(得分:0)

我认为您需要将范围设置为https://www.googleapis.com/auth/plus.login才能获得此stackoverflow用户建议的出生日期:

Retrieving date of birth and marital status with Google OAuth API

更多信息也可以在这里找到: https://developers.google.com/+/api/oauth#plus.login