28 March 2020

get access token from google oauth2 service account json file using jwt token

Here is a simple code snippet that takes google service account .json file as input and gives you access token with the specified scope.

<?php
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
$scope = 'https://www.googleapis.com/auth/drive';
$json=file_get_contents('service_account.json');
$key = json_decode($json);
$time=time();
$header = ['alg'=>'RS256','typ'=>'JWT'];
$claimset = ['iss'=>$key->client_email,'scope'=>$scope,'aud'=>$key->token_uri,'exp'=>$time+3600,'iat'=>$time];
$header_base64 = base64url_encode(json_encode($header));
$claimset_base64 = base64url_encode(json_encode($claimset));
openssl_sign($header_base64.".".$claimset_base64,$signature,$key->private_key,"SHA256");
$signature_base64 = base64url_encode($signature);
$jwt=implode('.',[$header_base64,$claimset_base64,$signature_base64]);
//echo $jwt;
$post=[];
$post['grant_type'] = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
$post['assertion']=$jwt;
$curl = curl_init($key->token_uri);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl);
$code = curl_getinfo($curl);
curl_close($curl);
$token = json_decode($response);
$access_token = $token->access_token;
//echo $access_token;


Hope it helps somebody who is in need of , or been searching for it.