代码之家  ›  专栏  ›  技术社区  ›  Dima

PHP-Google Admin SDK-使用“未授权访问此资源/api”的服务帐户进行身份验证

  •  1
  • Dima  · 技术社区  · 8 年前

    我正在使用库google/google api php客户端,我正在使用服务帐户创建身份验证。

    我已在中创建了服务帐户 https://console.developers.google.com/ 我将域名权限添加到我的服务帐户。

    但我返回时要求如下:

    Google_Service_Exception in REST.php line 118:
    {
    "error": {
    "errors": [
    {
    "domain": "global",
    "reason": "forbidden",
    "message": "Not Authorized to access this resource/api"
    }
    ],
    "code": 403,
    "message": "Not Authorized to access this resource/api"
    }
    }
    

    我的职能:

    $client = new \Google_Client();
    
    $credentials_file = base_path() . '/service-account.json';
    
    if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
        $client->setAuthConfig($credentials_file);
    }
    
    $client->setApplicationName("app-name");
    $client->setScopes([
        'https://www.googleapis.com/auth/admin.directory.user',
        'https://www.googleapis.com/auth/admin.directory.user.readonly'
    ]);
    
    $service = new \Google_Service_Directory($client);
    
    $userKey = 'user@domain.com';
    
    $results = $service->users->get($userKey);
    
    var_dump($results);
    

    如果我试着在这里工作。 https://developers.google.com/admin-sdk/directory/v1/reference/users/get#auth

    1 回复  |  直到 8 年前
        1
  •  5
  •   Dima    8 年前

    我可以解决这个问题。我在域上的用户管理员缺少设置主题:

    $client->setSubject("admin@yourdomain.com");
    

    结果:

    $client = new \Google_Client();
    
    $credentials_file = base_path() . '/service-account.json';
    
    if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
        $client->setAuthConfig($credentials_file);
    }
    
    $client->setApplicationName("app-name");
    $client->setSubject("admin@yourdomain.com");
    $client->setScopes([
        'https://www.googleapis.com/auth/admin.directory.user',
        'https://www.googleapis.com/auth/admin.directory.user.readonly'
    ]);
    
    $service = new \Google_Service_Directory($client);
    
    $userKey = 'user@domain.com';
    
    $results = $service->users->get($userKey);
    
    var_dump($results);