Google.Apis.Auth.OAuth2.Mvc 库和刷新令牌

Google.Apis.Auth.OAuth2.Mvc library and refresh token

我正在尝试从我们的企业帐户中检索评论。

为此,我使用 Google.Apis.Auth.OAuth2.Mvc .net https://www.nuget.org/packages/Google.Apis.Auth.MVC/ and following this example https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-asp.net-mvc.

图书馆应该自动使用刷新令牌,但由于某种原因,在访问令牌过期 1 小时后,我们无法访问评论。

这是我的实现:

public 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; }
    }
}
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);
    }
}
public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
{
    protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
    {
        get { return new AppFlowMetadata(); }
    }
}

评论来自我们自己的公司,因此我们不会接受不同用户的登录。我想要实现的是第一次使用我们公司的登录名登录,然后使用刷新令牌自动刷新访问令牌,以便评论始终在网站上可见,

非常感谢!

编辑:

1 小时后,我从以下代码得到的响应是这样的:

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

""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.\",\n "status": "UNAUTHENTICATED"

result.Credential 包含访问令牌和刷新令牌,因此它似乎读取了 app_data 中的文件。但是访问码好像过期了,此时没有刷新,也没有要求重新登录:

var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
        AuthorizeAsync(cancellationToken);

您实际上并不是在“告诉图书馆”刷新访问令牌,您是在直接使用已存储但现在已过期的令牌。您的代码如下所示:

var accessToken = result.Credential.Token.AccessToken;

应该是这样的:

var accessToekn = await result.Credential.GetAccessTokenForRequestAsync();

GetAccessTokenForRequestAsync 方法将检查访问令牌是否需要刷新并在需要时进行刷新。