Google OAuth 刷新令牌自动更新

Google OAuth Refresh Token Auto Update

我有一个发布状态为测试的项目(我正在使用 Google 广告 Api)。

            using FileStream stream = new("Credentials.json", FileMode.Open, FileAccess.Read);

            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.

            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
             GoogleClientSecrets.FromStream(stream).Secrets,
             scopes,
             "user",
             CancellationToken.None,
             new FileDataStore("Token", true)
            );

            if (credential.Token.IsExpired(credential.Flow.Clock))
                await credential.RefreshTokenAsync(CancellationToken.None);

当我使用上面的代码时,它希望我通过 Gmail 登录,但我想自动处理刷新令牌并继续不间断的请求,而无需向用户了解任何内容。我使用桌面应用程序作为流程,但我使用 Net 5 Api 作为框架。期待您在这件事上的帮助。

从现在开始谢谢你。

您遇到的问题与您的代码无关,而是您的应用仍处于测试阶段。

如果您查看 oauth2#expiration 的文档,您会发现它说

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

解决方案是将您的应用设置为正式版,然后您的刷新令牌将不再过期。

不确定为什么要发送 curl 请求来获取新的刷新令牌。这一切都可以用您拥有的代码来完成。