ASP.NET Core 7.0 MVC中如何获取Google登录AccessToken调用日历API
获取Google登录后的AccessToken以调用Calendar API
你已经在配置中设置了googleOptions.SaveTokens = true,这个配置会让ASP.NET Core将Google返回的令牌(包括AccessToken)保存到认证Cookie中,可通过以下步骤获取并使用:
- 在控制器中直接使用HttpContext:登录后用户的认证信息会绑定到
HttpContext.User,通过框架提供的方法即可提取令牌 - 调用
GetTokenAsync方法:指定令牌类型为OpenIdConnectParameterNames.AccessToken即可获取目标令牌
完整控制器示例代码
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Services; public class CalendarController : Controller { private const string ApplicationName = "你的应用名称"; public async Task<IActionResult> GetEvents() { // 校验用户是否已完成登录 if (!User.Identity.IsAuthenticated) { return Challenge(); // 未登录则触发Google登录流程 } // 从认证Cookie中提取AccessToken var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken); if (string.IsNullOrEmpty(accessToken)) { return BadRequest("无法获取有效的访问令牌"); } // 初始化Calendar服务并调用API GoogleCredential cred = GoogleCredential.FromAccessToken(accessToken); CalendarService service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = cred, ApplicationName = ApplicationName }); EventsResource.ListRequest request = service.Events.List("primary"); request.ShowDeleted = false; request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; Events events = await request.ExecuteAsync(); // 将事件数据传递到视图或进行后续处理 return View(events.Items); } }
注意事项
- 确保已安装必要的NuGet包:
Google.Apis.Calendar.v3和Microsoft.AspNetCore.Authentication.Google - 若AccessToken过期,可通过
HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken)获取刷新令牌,调用Google接口刷新令牌;也可配置Cookie认证选项,让框架自动处理令牌刷新逻辑
内容的提问来源于stack exchange,提问作者Sunny Leu
相关产品推荐
相关产品推荐

