如何在 MVC 中解决“访问令牌已过期但我们无法刷新它”

How to resolve 'The access token has expired but we can't refresh it' in MVC

我目前正在研究 Google Api 旨在让已登录 person.I 的圈子已经拥有 access token 但问题是每当我尝试 运行 我的代码时 returns 这个异常

The access token has expired but we can't refresh it

如何解决这个问题?

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<Person>();


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
};

User Credentials

UserCredential is a thread-safe helper class for using an access token to access protected resources. An access token typically expires after 1 hour, after which you will get an error if you try to use it.

UserCredential and AuthorizationCodeFlow take care of automatically "refreshing" the token, which simply means getting a new access token. This is done using a long-lived refresh token, which you receive along with the access token if you use the access_type=offline parameter during the authorization code flow.

In most applications, it is advisable to store the credential's access token and refresh token in persistent storage. Otherwise, you will need to present the end user with an authorization page in the browser every hour, because the access token expires an hour after you've received it.