【问题标题】:How to re-authenticate when upgrading the scope of the Google Drive API升级 Google Drive API 范围时如何重新认证
【发布时间】:2020-10-08 14:44:01
【问题描述】:

我有一个可以访问 Google Drive(TeamDrive 文件夹)的网络应用程序。它在 WordPress 和 PHP 上运行。它读取驱动器的内容并显示文件夹/文件并启用下载文件。一切正常,但现在我需要为其添加文件上传功能。当前范围是 DRIVE_READONLY,需要升级到 DRIVE 以允许写入(文件创建)功能。

我在代码中的任何地方都将范围更改为 DRIVE,并在 Google 控制台的 OAuth 同意屏幕中添加了 auth/drive 范围。然而,凭证 JSON 文件中的范围显示为“https://www.googleapis.com/auth/drive.readonly”。当尝试上传文件时,Google API 会响应错误“权限不足:请求的身份验证范围不足。”。我猜问题出在 json 中,我需要再次进行身份验证才能将凭据升级到新范围。

当我有一个在生产环境中启动并运行的应用程序时,我该怎么做?我找不到任何指导如何做到这一点。我应该在控制台中执行此操作,通过在应用程序或 CLI 中使用的用户登录还是如何?

代码是 PHP,它使用 Google API 客户端和在读取驱动器时运行良好的类,对驱动器上的内容进行搜索。

【问题讨论】:

  • 您是否在添加新范围后创建了新凭据,然后导出并使用了新的 JSON?
  • 您是指在 Google API 控制台中创建的客户端 ID 和客户端密码吗?不,我没有那样做。我假设这些仍然有效,并且需要使用新范围刷新令牌。
  • 明白了,你是对的。在这种情况下,您确定删除了在使用drive_readonly 时创建的token.json 吗?如果您不这样做,应用程序将不会创建新的,而是使用旧的。
  • 当我删除包含令牌的 json 时,应用程序停止工作。它无法访问 GDrive 并且不显示任何内容。它也不会创建新令牌。如果我撤消删除,那么它会再次正常工作,除了范围是只读的。
  • 你能分享你正在使用的代码吗?

标签: php google-drive-api


【解决方案1】:

您必须从命令行运行代码/脚本。当找不到凭据文件(您首先删除)时,该代码可以解决问题。当您在浏览器中打开该链接并重定向到您创建密钥时在 Google API 控制台中设置的 URL 时,您会发现验证码添加到了该 URL 的末尾。将其复制粘贴到命令行,代码将获取凭据文件并将其保存到硬盘。

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Web client file upload');
    $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('inc/client_secret_xxxxxx.apps.googleusercontent.com.json');
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('inc/credentials_xxxxxx.json');
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2022-10-06
    相关资源
    最近更新 更多