【问题标题】:How to resolve 'The access token has expired but we can't refresh it' in MVC如何在 MVC 中解决“访问令牌已过期但我们无法刷新它”
【发布时间】:2016-07-18 07:52:18
【问题描述】:

我目前正在开发 Google Api,它旨在获取已登录人的圈子。我已经拥有 访问令牌,但问题是每当我尝试运行我的代码它返回这个异常

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

我该如何解决这个问题?

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

}

【问题讨论】:

    标签: c# model-view-controller google-api google-api-dotnet-client


    【解决方案1】:

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

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

    User Credentials

    UserCredential 是一个线程安全的帮助类,用于使用访问令牌 访问受保护的资源。 访问令牌通常在 1小时,之后尝试使用会报错

    UserCredential 和 AuthorizationCodeFlow 自动处理 “刷新”令牌,这仅仅意味着获得一个新的访问令牌。 这是使用您收到的长期刷新令牌完成的 如果您使用 access_type=offline 参数,则使用访问令牌 在授权码流程中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 2021-11-16
      • 2021-12-05
      • 2017-10-28
      • 2020-06-12
      • 2014-01-01
      • 2021-08-25
      • 2021-12-19
      相关资源
      最近更新 更多