Google Calendar API - PHP oauth2callback.php 身份验证.php

问题描述 投票:1回答:1

我目前使用的是 谷歌日历API 的网络应用。但是,每隔一个小时,我就会被提示一个验证快速启动访问的链接。有人知道如何解决这个问题吗?

详情请看。

  • 我创建了一个新的Gmail ID:[email protected]
  • [email protected] 有一个相关的日历
  • 我的基于php的web应用程序需要对日历进行以下操作。
  • 为每个注册用户创建一个新的日历(作为[email protected] 的附加日历)
  • 为一个已登录的用户创建一个事件,并添加另一个已注册的用户作为被邀请者。

我试过用OAUTH和服务账号,都没有效果。 任何帮助是非常感激的。

以下是使用服务账户的凭证创建Google_Client和Srvice对象的代码。

function __construct()
    {
        Service account based client creation. 
        $this->client = new Google_Client();
        $this->client->setApplicationName("Redu");
        $this->client->setAuthConfig(CREDENTIALS_PATH);
        $this->client->setScopes([SCOPES]);
        $this->client->setSubject('[email protected]');
        $this->client->setAccessType('offline');

        $this->service = new Google_Service_Calendar($this->client);
     }

当我试图使用$service对象创建一个日历或创建一个事件时,我得到一个错误,说域范围的权限没有设置。 然而,当我创建服务帐户时,我确实启用了域范围的授权。

EDIT:

下面是我的代码,使用服务账户密钥创建一个Google_Client,并使用客户端为[email protected] 创建一个新的日历。请注意,我将[email protected]的日历与[email protected]共享,并将权限设置为 "管理更改和管理共享"。 我得到的错误就在下面的代码中。

require (__DIR__.'/../../../vendor/autoload.php');
define('CREDENTIALS_PATH', __DIR__ . '/redu_service_account_credentials.json');
define('SCOPES', Google_Service_Calendar::CALENDAR);

function createNewCalendar($userName) {
    //Service account based client creation. 
    $client = new Google_Client();
    $client->setApplicationName("REdu");
     // path to the credentials file obtained upon creating key for service account
    $client->setAuthConfig(CREDENTIALS_PATH);
    $client->setScopes([SCOPES]);
    $client->setSubject('[email protected]');
    $client->setAccessType('offline');

    $service = new Google_Service_Calendar($client);

    $calendar = new Google_Service_Calendar_Calendar();
    $calendar->setSummary($userName);
    $calendar->setTimeZone('America/Los_Angeles');

    $createdCalendar = $service->calendars->insert($calendar);

    // Make the newly created calendar public
    $rule = new Google_Service_Calendar_AclRule();
    $scope = new Google_Service_Calendar_AclRuleScope();

    $scope->setType("default");
    $scope->setValue("");
    $rule->setScope($scope);
    $rule->setRole("reader");

    // Make the calendar public
    $createdRule = $service->acl->insert($createdCalendar->getId(), $rule);
    return $createdCalendar->getId();
}

ERROR:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
  "error": "unauthorized_client",
  "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
}'
php google-api google-calendar-api google-oauth google-api-php-client
1个回答
0
投票

OAUTH2与服务账户

Oauth2和服务账户是两码事。 如果你试图访问一个用户的数据,你使用oauth2。你提到的同意窗口将被撑起,并要求他们允许你的应用程序访问他们的数据。

另一方面,服务账户是虚拟用户,他们可以被预先批准访问你这个开发者控制的数据。 你可以与一个服务账户共享一个日历,授予它访问该日历的权限,它将不需要像用户一样进行身份验证。

一个服务账户将永远不会弹出并再次请求访问。

带刷新令牌的Oauth2例子。

问题是你的访问令牌正在过期。 如果它过期了,那么用户将需要再次授予你的应用程序对其数据的访问权。为了避免这种情况,我们使用刷新令牌,并将其存储在一个会话变量中,当访问令牌过期时,我们只需请求一个新的令牌。

请注意我是如何请求 $client->setAccessType("offline"); 这将给我一个刷新标记。

会话变量现在被设置为存储这些数据。

    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();  

然后,我可以检查访问令牌是否过期,如果过期,我就刷新它。

 if ($client->isAccessTokenExpired()) {             
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($client->getAccessToken());   
            $_SESSION['access_token'] = $client->getAccessToken();                
        }       

oauth2callback.php

    require_once __DIR__ . '/vendor/autoload.php';
    require_once __DIR__ . '/Oauth2Authentication.php';
    
    // Start a session to persist credentials.
    session_start();
    
    // Handle authorization flow from the server.
    if (! isset($_GET['code'])) {
        $client = buildClient();
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client = buildClient();
        $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
        // Add access token and refresh token to seession.
        $_SESSION['access_token'] = $client->getAccessToken();
        $_SESSION['refresh_token'] = $client->getRefreshToken();    
        //Redirect back to main script
        $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

认证.php

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();

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

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  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 buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}


/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {
        
        $client = buildClient();
        
        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }
        
        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            
            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 
            
            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
?>

账号密码

凭证文件是不同的,不要把它们混在一起。

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

}

错误

客户端未经授权使用此方法检索访问令牌,或者客户端未被授权使用任何请求的范围。

有两种类型的客户端Oauth2客户端和服务账户客户端。 你下载的.json文件对于每个客户端都是不同的。 就像你将为每个客户端使用的代码一样。 你不能交换这些代码。

你得到的错误统计,你正在使用的客户端不能用于你正在使用的代码。 试着再次下载服务账户的客户端秘密.json......。

© www.soinside.com 2019 - 2024. All rights reserved.