如何在ASP.NET MVC应用中通过Google登录获取用户出生日期
解决ASP.NET MVC中Google认证无法获取出生日期的问题
默认的Microsoft.AspNetCore.Authentication.Google中间件只会从Google的基础用户信息端点返回姓名、邮箱等核心数据,出生日期并不在默认返回范围内,需要额外调用Google People API来获取。以下是具体解决步骤:
1. 完善认证配置,保存访问令牌
在Startup的Google认证配置中添加SaveTokens = true,这样认证成功后会将Access Token保存到认证票据中,用于后续调用API:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie() .AddGoogle(options => { options.ClientId = _configuration["GoogleLogin:ClientId"]; options.ClientSecret = _configuration["GoogleLogin:ClientSecret"]; options.AccessDeniedPath = "/login"; options.Scope.Add("https://www.googleapis.com/auth/plus.login"); options.Scope.Add("https://www.googleapis.com/auth/userinfo.email"); options.Scope.Add("https://www.googleapis.com/auth/userinfo.profile"); options.Scope.Add("https://www.googleapis.com/auth/user.birthday.read"); // 保存访问令牌,用于调用People API options.SaveTokens = true; });
2. 调用Google People API获取出生日期
在控制器中,从认证结果中取出Access Token,然后请求People API获取用户的出生日期:
var authResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); if (authResult.Succeeded) { // 从认证属性中获取Access Token var accessToken = authResult.Properties.GetTokenValue("access_token"); if (!string.IsNullOrEmpty(accessToken)) { using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); // 请求People API,指定只获取出生日期字段 var response = await httpClient.GetAsync("https://people.googleapis.com/v1/people/me?personFields=birthdays"); if (response.IsSuccessStatusCode) { var personData = await response.Content.ReadFromJsonAsync<GooglePersonResponse>(); var birthdayEntry = personData?.Birthdays?.FirstOrDefault(); if (birthdayEntry != null) { // 解析出生日期 var birthDate = new DateTime( birthdayEntry.Date.Year, birthdayEntry.Date.Month, birthdayEntry.Date.Day ); // 后续业务逻辑处理 } } } } // 用于解析API响应的模型类 public class GooglePersonResponse { public List<BirthdayInfo> Birthdays { get; set; } } public class BirthdayInfo { public DateDetails Date { get; set; } } public class DateDetails { public int Year { get; set; } public int Month { get; set; } public int Day { get; set; } }
关键注意事项
- 启用People API:必须登录Google Cloud Console,在「API和服务」中搜索并启用「People API」,否则API请求会返回权限错误。
- 用户授权验证:确保用户的Google账号中已填写出生日期,且在登录时授权了应用访问该信息。
- 可选优化:可以使用Google官方客户端库
Google.Apis.PeopleService.v1来替代手动HttpClient调用,简化API交互逻辑。
内容的提问来源于stack exchange,提问作者Deepanshu Chauhan
相关产品推荐
相关产品推荐

