Php Google Drive Auth:从JSON版本的私钥创建JWT签名

Php Google Drive Auth:从JSON版本的私钥创建JWT签名,php,jwt,private-key,sign,Php,Jwt,Private Key,Sign,我在为Google Drive授权创建JWT时遇到问题。 说明在中给出 我已经设法解决了这个问题。下面是更新后的代码,它读取从Google下载的JSON文件,并创建一个断言,使用该断言可以从Google获得访问令牌: <?php //helper function function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } // Read the JS

我在为Google Drive授权创建JWT时遇到问题。 说明在中给出


我已经设法解决了这个问题。下面是更新后的代码,它读取从Google下载的JSON文件,并创建一个
断言
,使用该断言可以从Google获得访问令牌:

<?php
//helper function
function base64url_encode($data) { 
return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

// Read the JSON credential file my-private-key.json download from Google
$private_key_file="my-private-key.json";
$json_file = file_get_contents($private_key_file);

$info = json_decode($json_file);
$private_key = $info->{'private_key'};

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => $info->{'client_email'},
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

$data = $jwtHeader.".".$jwtClaim;

// Signature
$Sig = '';
openssl_sign($data,$Sig,$private_key,'SHA256');
$jwtSign = base64url_encode( $Sig  );


//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}

$jwtAssertion = $data.".".$jwtSign;
echo "$jwtAssertion\n";

我已经设法解决了这个问题。下面是更新后的代码,它读取从Google下载的JSON文件,并创建一个
断言
,使用该断言可以从Google获得访问令牌:

<?php
//helper function
function base64url_encode($data) { 
return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

// Read the JSON credential file my-private-key.json download from Google
$private_key_file="my-private-key.json";
$json_file = file_get_contents($private_key_file);

$info = json_decode($json_file);
$private_key = $info->{'private_key'};

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => $info->{'client_email'},
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

$data = $jwtHeader.".".$jwtClaim;

// Signature
$Sig = '';
openssl_sign($data,$Sig,$private_key,'SHA256');
$jwtSign = base64url_encode( $Sig  );


//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}

$jwtAssertion = $data.".".$jwtSign;
echo "$jwtAssertion\n";
curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=YOUR-JWT-ASSERTION-BUILD-ABOVE' https://www.googleapis.com/oauth2/v4/token