我试图通过Google Oauth2获得生日 但不确定我是否正确行事......
以下是我使用的代码:
var googleAuthOptions = new GoogleOAuth2AuthenticationOptions();
googleAuthOptions.ClientId = googleId;
googleAuthOptions.ClientSecret = googleSecret;
googleAuthOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
googleAuthOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.profile");
googleAuthOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
googleAuthOptions.Provider = new GoogleOAuth2AuthenticationProvider
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
var expiryDuration = context.ExpiresIn ?? new TimeSpan();
context.Identity.AddClaim(new Claim("google:expires_in", DateTime.UtcNow.Add(expiryDuration).ToString(CultureInfo.InvariantCulture)));
if (context.Email != null) context.Identity.AddClaim(new Claim("google:email", context.Email));
if (context.Id != null) context.Identity.AddClaim(new Claim("google:id", context.Id));
if (context.GivenName != null) context.Identity.AddClaim(new Claim("google:given_name", context.GivenName));
if (context.FamilyName != null) context.Identity.AddClaim(new Claim("google:family_name", context.FamilyName));
if (context.Name != null) context.Identity.AddClaim(new Claim("google:name", context.Name));
if (context.Profile != null) context.Identity.AddClaim(new Claim("google:profile", context.Profile));
if (context.User.GetValue("birthday") != null) context.Identity.AddClaim(new Claim("google:birthday", context.User.GetValue("birthday").ToString()));
if (context.User.GetValue("locale") != null) context.Identity.AddClaim(new Claim("google:locale", context.User.GetValue("locale").ToString()));
if (context.User.GetValue("gender") != null) context.Identity.AddClaim(new Claim("google:gender", context.User.GetValue("gender").ToString()));
if (context.User.GetValue("picture") != null) context.Identity.AddClaim(new Claim("google:picture", context.User.GetValue("picture").ToString()));
// Add all other available claims
foreach (var claim in context.User)
{
var claimType = string.Format("google:{0}", claim.Key);
var claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
}
return Task.FromResult(0);
}
};
app.UseGoogleAuthentication(googleAuthOptions);
我很想看到有效的代码示例
提前致谢。
答案 0 :(得分:1)
已解决,除了设置正确的范围(https://www.googleapis.com/auth/plus.login)
之外确保您的Google Plus测试帐户个人资料允许"显示生日年份"此外,生日可供公众"
使用如果这还不够,Google也会以yyyy / mm / dd格式发送生日... 所以我用它来显示MM / dd / yyyy
DateTime dateDateOfBirth;
DateTime.TryParse(vm.DateOfBirth, out dateDateOfBirth);
if (DateAndTime.IsDateValid(vm.DateOfBirth))
{
// By default Google returns yyyy/mm/dd
vm.DateOfBirth = dateDateOfBirth.ToString(@"MM/dd/yyyy");
}
else vm.DateOfBirth = string.Empty;