【问题标题】:How to get Google's OAuth API to refresh token automatically?如何让 Google 的 OAuth API 自动刷新令牌?
【发布时间】:2022-01-07 16:49:31
【问题描述】:

大家好!我有以下代码来设置我的 Google API:

                // Open the FileStream to the related file.
                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,
                    new[] { SheetsService.Scope.Spreadsheets, YouTubeService.Scope.YoutubeReadonly },
                    "admin",
                    CancellationToken.None,
                    new FileDataStore("Token", true),
                    new PromptCodeReceiver()
                );

                // Create Google Sheets API service.
                builder.Services.AddSingleton(new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = name,
                }));

                // Create Youtube API service.
                builder.Services.AddSingleton(new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = name,
                }));

使用此代码,我的所有服务都正确地注入到我正在使用的服务提供者中。但是,经过 7 天的 ASP.Net 网站似乎没有刷新令牌,即使我的令牌文件有一个刷新令牌。正如我想象的那样,这是因为 OAuth 令牌仅持续 7 天。

那么,如何让 Google 的 API 自动刷新我的令牌?由于这是一个网站,它需要长时间在线而不因令牌过期而停机。

【问题讨论】:

    标签: asp.net google-api google-oauth youtube-data-api google-api-dotnet-client


    【解决方案1】:

    如果您的应用仍在测试中,则刷新令牌会在 7 天后过期。要让它们过期更长时间,您需要将您的应用设置为生产环境,并可能对其进行验证。

    Refresh token expiration

    为外部用户类型配置了 OAuth 同意屏幕且发布状态为“正在测试”的 Google Cloud Platform 项目发出了一个在 7 天后到期的刷新令牌。

    网络应用与已安装应用

    我很惊讶您的代码托管在网站上。 GoogleWebAuthorizationBroker.AuthorizeAsync 适用于已安装的应用程序。它不适用于托管在网站上的 Asp .net。它不起作用的原因是它会导致同意浏览器在运行代码的机器上打开。这将在开发中起作用,但一旦您尝试将其托管在网络服务器上,它就无法正常工作,因为服务器无法生成本地网络浏览器。

    你应该关注Web applications (ASP.NET Core 3)

    哪个会使用依赖注入

    public void ConfigureServices(IServiceCollection services)
    {
        ...
    
        // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
        services
            .AddAuthentication(o =>
            {
                // This forces challenge results to be handled by Google OpenID Handler, so there's no
                // need to add an AccountController that emits challenges for Login.
                o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
                // This forces forbid results to be handled by Google OpenID Handler, which checks if
                // extra scopes are required and does automatic incremental auth.
                o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
                // Default scheme that will handle everything else.
                // Once a user is authenticated, the OAuth2 token info is stored in cookies.
                o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddGoogleOpenIdConnect(options =>
            {
                options.ClientId = {YOUR_CLIENT_ID};
                options.ClientSecret = {YOUR_CLIENT_SECRET};
            });
    }
          
    

    您无需担心刷新访问令牌,库会为您处理。

    【讨论】:

    • 我明白了!就是这样,我相信它目前正在测试中。我现在就验证!
    • 听到有关网络/已安装应用程序的信息真的很有趣,很好!以后可能省了很多麻烦哈哈。
    • 专业提示:在完成验证过程之前,您将无法发布公开视频。
    【解决方案2】:

    是不是让 ASP.NET 应用访问 Youtube 和 Sheets...

    1. 代表最终用户
    2. 代表自己(不涉及最终用户?

    在 (1) 的情况下,使用 GoogleWebAuthorizationBroker 启动 OAuth 授权流程是正确的方法,但您可能不应该永久存储刷新令牌。要么仅在最终用户会话期间存储它,要么根本不存储它并在每次访问令牌过期时触发新的 OAuth 授权流程。

    在 (2) 的情况下,您应该使用服务帐户和load credentials by using GoogleCredentials.GetApplicationDefaultAsync()。如果应用在 Google Cloud 上运行,attach a service account to the underlying compute resource;如果它在其他地方运行you can use Workload identity federation or service account keys

    【讨论】:

    • 刷新令牌用于离线访问,为什么您不将它们与用户登录信息一起存储在数据库中。您想在用户每次返回您的网站时征求他们的同意吗?这个问题的作者正在使用不支持服务帐户的 YouTube API。 (-1 表示不正确的信息。)
    • 至少有一些 YouTube API 确实支持服务帐户。
    • YouTube 数据 API 均不支持服务帐户。如果您认为确实如此,请链接 API 和说明它的文档。我已经使用这些 API 11 年了,如果你能证明我错了,我会非常高兴。
    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 2015-02-25
    • 2016-02-19
    • 2016-09-10
    • 2017-12-20
    • 2014-07-15
    • 2016-08-21
    相关资源
    最近更新 更多