1

我正在尝试从 Google 获取访问令牌,以便我可以使用“服务帐户”将视频自动上传到 YouTube。

这段代码:

$credentials = array(
        'client_id' => $my_client_id
    );

$jwt = JWT::encode($credentials, $private_key);

$client = new Google_Client();

if ($client->authenticate($jwt))
{
   // do something
}

失败并出现此异常:

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_request: Client must specify either client_id or client_assertion, not both'' in /home/google/client/google-api-php-client/src/Google/Auth/OAuth2.php:120

我哪里错了?

泰!

4

2 回答 2

1

我错过了大部分文档,如下所示:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#creatingjwt

我还错过了该算法必须是 RSA256 而不是 HSA256,因为 JWT PHP 编码函数中默认使用该算法。

此外,我需要适当地直接发布请求以获取对端点的访问令牌:

https://www.googleapis.com/oauth2/v3/token

由于最终字符被编码/包含为:

\u003d

从字面上看,交换这个:

=

解决了那个问题。

这是我现在工作的(ish,见结束语)代码:

$claimset = array(
        'iss'          => $client_email,
        'scope'        => 'https://www.googleapis.com/auth/youtube.upload',
        'aud'          => 'https://www.googleapis.com/oauth2/v3/token',
        'exp'          => time() + 1800,
        'iat'          => time(),
        'sub'          => 'my google account email@gmail.com'); // not sure if reqd

$jwt = JWT::encode($claimset, $private_key, 'RS256');

// Now need to get a token by posting the above to:
// https://www.googleapis.com/oauth2/v3/token

# Our new data
$data = array(
      'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      'assertion'  => $jwt
    );

# Create a connection
$url = 'https://www.googleapis.com/oauth2/v3/token';
$ch = curl_init($url);

# Form data string
$postString = http_build_query($data, '', '&');

# Setting our options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

# Get the response
$response = curl_exec($ch);
curl_close($ch);

print "and here is what we got: ";
print_r($response);
exit;

不幸的是,由于某种原因,我得到的回应是:

{ "error": "unauthorized_client", "error_description": "未经授权的客户端或请求范围。" }

怀疑我的服务帐号还没有上传到 YouTube 的权利。

于 2014-12-12T22:11:16.443 回答
0

我不是专家,但您可能应该考虑在此处删除行尾的“,”:

'client_id'    => $private_key['client_id'],
//'client_email' => $private_ket['client_email']

改成:

'client_id'    => $private_key['client_id']
//'client_email' => $private_ket['client_email']

我用这个例子来让 oauth 工作。这可能会有所帮助:http: //msdn.microsoft.com/en-us/library/dn632721.aspx

你也可以在这里尝试 oauth 测试: https ://developers.google.com/oauthplayground/

祝你好运!

于 2014-12-12T13:28:02.350 回答