1

「サービス アカウント」を使用して YouTube に動画を自動的にアップロードできるように、Google からアクセス トークンを取得しようとしています。

このコード:

$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

また、JWT PHP エンコード関数でデフォルト設定されているように、アルゴリズムが HSA256 ではなく RSA256 でなければならないことも見逃していました。

さらに、エンドポイントへのアクセス トークンを取得するために、適切に直接リクエストを POST する必要がありました。

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

サービス アカウントの Google 秘密 JSON 秘密鍵も、最後の文字が次のようにエンコード/含まれているため、openssl での使用には無効でした。

\u003d

これを、文字通り、次のものと交換します。

=

その問題を解決しました。

これが私の現在の作業中のコードです(最後のステートメントを参照してください):

$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 に答える