so I'm trying to use the Google vision API in php but with out using the SDK as while I got composer on my test system, I just know there's going to be a situation in one of the client servers where composer will not be available. So thus I can't use it to install any of that. I was following the guides and I'm stuck on how to authenticate,I want to use a service account as I also know that one of the likely requirements will be that no one has to manually log in at the start as this will likely only be one piece of a larger puzzle and that would be very impractical.
so I've followed several guides and ended up with this code, it does produce what looks like a valid JWT but when I try hit up the end point I get:
{ "error": "unsupported_grant_type", "error_description": "Invalid grant_type: " }
using this code, I can't figure out why as according to I'm using the correct grant type. what am I missing?
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
//$headers = [ "alg"=>"RS256","typ"=>"JWT" ];
$headers=array();
$headers["alg"] = "RS256";
$headers["typ"] = "JWT";
$headers["kid"]="251.........d6";
$headers_encoded = base64UrlEncode(json_encode($headers));
$issuedAt = time();
$payload =
[
"id" =>random_int(0,9999999999),//gen_uuid(), // .setId(UUID.randomUUID().toString())
"sub"=> "[email protected]", //Subject
"iss"=> "[email protected]", //issuer
"iat"=> $issuedAt, //issued at
"exp"=> $issuedAt+3600,
"target_audience"=> ":annotate",
"scope"=> ":annotate",
"aud" => ";
];
$payload_encoded = base64UrlEncode(json_encode($payload));
/*
//build the signature hmac
$key = 'secret';
$signature = hash_hmac('sha256',"$headers_encoded.$payload_encoded",$key,true);
$signature_encoded = base64UrlEncode($signature);
//build and return the token
*/
//build the signature
$key = "-----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----\n";
openssl_sign("$headers_encoded.$payload_encoded", $signature, $key, 'sha256WithRSAEncryption');
$signature_encoded = base64UrlEncode($signature);
$token = $headers_encoded.$payload_encoded.$signature_encoded;
//echo $token;
$ch = curl_init(";);
$header = array();
//$header[]="Authorization: Bearer ".$token;
$header[]="Content-Type: application/x-www-form-urlencoded";
$rbody=Array();
$robody["assertion"]=$token;
//$robody["grant_type"]=urlencode("urn:ietf:params:oauth:grant-type:jwt-bearer");
//$robody=json_encode($rbody);
$robody="grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rbody);
$out=curl_exec($ch);
if(curl_error($ch)) {
echo "ERROR:<br>". curl_error($ch);
}
else {echo $out;}
curl_close($ch);