Google.Apis.Auth.OAuth2.Mvc库访问令牌到期无法自动刷新拉取商家评论
问题背景
开发者需要从自有Google商家账户拉取门店用户评论,在.NET项目中引入Google.Apis.Auth.OAuth2.Mvc授权库,参考官方ASP.NET MVC Web应用OAuth实现指南完成授权逻辑开发。按照授权库的设计预期,系统应自动借助refresh token完成access token的续期,但实际运行中,access token1小时有效期届满后,程序便无法正常访问评论接口。
现有核心实现
- 自定义授权流程元数据类
AppFlowMetadatapublic class AppFlowMetadata : FlowMetadata { private static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "xxxxxxxxxxxxxxxxxxxxxxxxx", ClientSecret = "xxxxxxxxxxxxxxxxxxxxx" }, Scopes = new string[] { "https://www.googleapis.com/auth/plus.business.manage" }, DataStore = new FileDataStore(System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage"), true) //DataStore = new FileDataStore(System.Web.HttpContext.Current.Server.MapPath("/App_Data/Drive.Api.Auth.Store")) }); public override string GetUserId(Controller controller) { return "our email address"; } public override IAuthorizationCodeFlow Flow { get { return flow; } } } - 首页
IndexAsync方法逻辑:完成授权校验后获取access token,通过RestClient调用Google My Business v4接口拉取指定账户、指定门店的评论数据并渲染页面public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken) { var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential != null) { var accessToken = result.Credential.Token.AccessToken; var client = new RestClient("https://mybusiness.googleapis.com/v4/accounts/116326379071192580211/locations/6608127685860731136/reviews?access_token=" + accessToken); var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); GoogleReviewsModel googleReviews = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleReviewsModel>(response.Content); return View("Index", googleReviews); } else { return new RedirectResult(result.RedirectUri); } } - 授权回调控制器
AuthCallbackController:重写FlowData属性返回AppFlowMetadata实例,完成授权回调处理public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController { protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData { get { return new AppFlowMetadata(); } } }
核心业务诉求
- 仅需拉取自有公司的评论数据,无需支持多用户登录
- 首次通过公司账号完成授权登录后,后续可依托存储的refresh token自动续期access token,保证网站端的评论内容可长期稳定展示
故障表现
- access token到期1小时后,执行接口调用逻辑时返回未认证错误,返回报文为:
{ "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } - 经排查:
result.Credential中同时存储了access token与refresh token,程序也可正常读取App_Data目录下的授权存储文件,但access token到期后未触发自动刷新流程,也不会跳转重新登录授权页面。核心授权校验逻辑为:
该逻辑执行完成后,返回的Credential对象始终携带已过期的旧access token,无法支撑后续接口调用。var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);
内容的提问来源于stack exchange,提问作者Bryan Miguel
相关产品推荐
相关产品推荐

