JWT和PHP的问题

时间:2016-09-30 03:41:53

标签: php google-oauth google-spreadsheet-api

我需要为我的服务帐户获取一个访问令牌,该帐户是在我的Google控制台中创建的,用于获取Google电子表格服务的私人访问权限!

我的用于测试的php文件:

<?php

function base64_url_encode($input) {
    return strtr(str_replace('=', '', base64_encode($input)), '+/', '-_');
}

header('Content-type: text/plain');

$header = '{"alg":"RS256","typ":"JWT"}';

$payload =
'{
  "iss":"[my service account]@[my project name].iam.gserviceaccount.com",
  "scope":"https://www.googleapis.com/auth/spreadsheets",
  "aud":"https://www.googleapis.com/oauth2/v4/token",
  "exp":'.(time() + 3600).',
  "iat":'.(time()).'
}';


include('Crypt/RSA.php');

$rsa = new Crypt_RSA();

$private_key = "-----BEGIN PRIVATE KEY-----[my private key from google console json file of my service account]-----END PRIVATE KEY-----\n";

//$rsa->setPassword('password');
$rsa->loadKey($private_key); // private key

$plaintext = base64_url_encode($header).'.'.base64_url_encode($payload);

$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
$signature = $rsa->sign($plaintext);

//$rsa->loadKey($rsa->getPublicKey()); // public key
//echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';

$jwt =  base64_url_encode($header).'.'.base64_url_encode($payload).'.'.base64_url_encode($signature);



$query = http_build_query(Array('grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt));

//echo $query;

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => $query
    )
);

$context  = stream_context_create($options);

$access_token = file_get_contents('https://www.googleapis.com/oauth2/v4/token', false, $context);

?>

php输出:

file_get_contents(https://www.googleapis.com/oauth2/v4/token) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

如果我在wfetch中运行相同的查询(来自php脚本的“$ query”变量):

HTTP/1.1 400 Bad Request\r\n
{\n
 "error": "invalid_grant",\n
 "error_description": "Invalid JWT Signature."\n
}\n

P.S。我的php版本是PHP 5.2(没有命名空间支持),也使用了phpseclib1.0.3。

P.P.S。尝试将RS256更改为HS256并且谷歌仍然响应400 - 无效的JWT签名,但是如果更改为不存在XX256(例如) - &gt;谷歌回复500 - 错误:internal_failure。所以我认为谷歌也可能支持HS256。如果这是真的 - 我可以使用mutch更简单的HS256方法。我发现了这个:https://github.com/progrium/php-jwt/blob/master/JWT.php

1 个答案:

答案 0 :(得分:1)

这是一个裸露的openssl / curl的完整示例:

<?php

$url = "https://www.googleapis.com/oauth2/v4/token";
$scope = 'https://www.googleapis.com/auth/spreadsheets';

$client_id = 'xxxxx@developer.gserviceaccount.com';
$p12 = 'google-api-xxxxx.p12';
$p12pwd = 'notasecret';

function base64_url_encode($input) {
    return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}

$iat = time();
$jwt_data = array(
    'iss' => $client_id,
    'aud' => $url,
    'scope' => $scope,
    'exp' => $iat + 3600,
    'iat' => $iat,
);

openssl_pkcs12_read(file_get_contents($p12), $certs, $p12pwd);
$header = array('typ' => 'JWT', 'alg' => 'RS256');
$signing_input = base64_url_encode(json_encode($header)) . '.' . base64_url_encode(json_encode($jwt_data));
openssl_sign($signing_input, $signature, $certs['pkey'], 'SHA256');
$jwt = $signing_input . '.' . base64_url_encode($signature);

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

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch) ;
echo $response;
?>