使用来自php的Google Drive API“无”身份验证屏幕

时间:2020-05-03 12:12:57

标签: php google-drive-api google-oauth google-api-php-client service-accounts

这是我面临的情况。 我有一个由php驱动的网络应用程序,需要从其中访问我在Google云端硬盘帐户中拥有的文件的某些链接。我只需要访问我帐户中的文件,因为我存储的图像必须服务于不同的客户。 我试图查看Google Drive API文档,但不需要OAuth和同意屏幕。该应用程序应该在“后台”访问我的Google云端硬盘帐户,只是为了检索必须向客户提供的一些信息,而无需他们做任何事情。

我在StackOverflow上阅读了非常类似的问题,但是这些问题都没有真正帮助我...有些人提到了服务帐户的使用,其他人则说它们对此目的没有用。

您能否帮助我了解在这种情况下哪种方法最好?提前非常感谢!

1 个答案:

答案 0 :(得分:3)

您正在寻找的是服务帐户。服务帐户是虚拟用户,他们实际上拥有自己的Google云端硬盘帐户。由于他们是用户,因此您可以像其他任何用户一样与他们共享文件。与服务帐户共享文件后,它就可以访问该文件,然后可以像登录Oauth2一样使用该文件,而无需登录,因为您已经配置了访问权限,所以无需登录并同意访问。

require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');

/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
相关问题