PHP JWT token authentication failed to apple store connect API
- I want to get data from API provided by Apple and I generate and pass jwt token I get NOT_AUTHORIZED 401 error.
Following code :
function generate_token(){
$AuthKey = storage_path('app/public/SubscriptionKey_N8JR******.p8');
$strKey=file_get_contents($AuthKey);
$strUrl = "https://api.appstoreconnect.apple.com/v1/users";
// $dHeader = array("kid" => "N8JR****", "typ" => "JWT");
$dHeader = array("alg" => "ES256", "kid" => "N8JR*****", "typ" => "JWT");
$strHeader = json_encode($dHeader);
$strBase64Header = $this->base64url_encode($strHeader);
// $dPayLoad = array("iss" => "3J6H*******", "exp"=>time()+1200, "aud"=>"appstoreconnect-v1");
$dPayLoad = array("iss" => "3J6H*******", "iat" => time(), "exp"=>time()+1200, "aud"=>"appstoreconnect-v1", "bid"=>"com.yourdomain.app");
$strPayLoad = json_encode($dPayLoad);
$strBase64PayLoad = $this->base64url_encode($strPayLoad);
$strContent = $strBase64Header . '.' . $strBase64PayLoad;
$strAlgName = "sha256";
$strSignature = $this->base64url_encode(hash_hmac($strAlgName, $strContent, $strKey));
$strToken = $strBase64Header . '.' . $strBase64PayLoad . '.' . $strSignature;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.appstoreconnect.apple.com/v1/users",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer ".$strToken
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo "<pre>";
if ($err) {
echo "cURL Error #:" . $err."<br>";
print_r(json_decode($response));
} else {
print_r(json_decode($response));
}
}
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
Result below :
stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[status] => 401
[code] => NOT_AUTHORIZED
[title] => Authentication credentials are missing or invalid.
[detail] => Provide a properly configured and signed bearer token, and make sure that it has not expired. Learn more about Generating Tokens for API Requests https://developer.apple.com/go/?id=api-generating-tokens
)
)
)
I used this https://github.com/ikool-cn/appstoreconnectapi-php-jwt-sign git source code. The token is generated but when I use that token in another API I get a not authorized error.