如何在MVC中解析’访问令牌已过期,但我们无法刷新它’

我目前正致力于谷歌Api ,旨在获得一个登录人员的圈子。我已经拥有访问令牌,但问题是每当我尝试运行我的代码时它返回此exception

访问令牌已过期但我们无法刷新它

我该如何解决这个问题?

var claimsforUser = await UserManager.GetClaimsAsync(User.Identity.GetUserId()); var access_token = claimsforUser.FirstOrDefault(x => x.Type == "urn:google:accesstoken").Value; string[] scopes = new string[] {PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile}; var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "xx-xx.apps.googleusercontent.com", ClientSecret = "v-xx", }, Scopes = scopes, DataStore = new FileDataStore("Store"), }); var token = new TokenResponse { AccessToken = access_token, ExpiresInSeconds=50000}; var credential = new UserCredential(flow, Environment.UserName, token); PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "ArcaneChatV2", }); PeopleResource.ListRequest listPeople = service.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible); listPeople.MaxResults = 10; PeopleFeed peopleFeed = listPeople.Execute(); var people = new List(); while (peopleFeed.Items != null) { foreach (Person item in peopleFeed.Items) { people.Add(item); } if (peopleFeed.NextPageToken == null) { break; } listPeople.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = listPeople.Execute(); } 

假设您已经拥有刷新令牌,则在创建TokenResponse时包含刷新令牌

 var token = new TokenResponse { AccessToken = access_token, RefreshToken = refresh_token }; 

用户凭据

UserCredential是一个线程安全的帮助程序类,用于使用访问令牌访问受保护的资源。 访问令牌通常在1小时后过期,之后如果您尝试使用它,您将收到错误

UserCredential和AuthorizationCodeFlow自动“刷新”令牌,这意味着获取新的访问令牌。 这是使用长期刷新令牌完成的,如果在授权代码流期间使用access_type = offline参数,则会与访问令牌一起使用。

在大多数应用程序中,建议将凭证的访问令牌和刷新令牌存储在持久存储中。 否则,您需要每小时在浏览器中向最终用户显示一个授权页面,因为访问令牌在您收到后一小时后到期。