cesarcarlos
cesarcarlos

Reputation: 1405

JWT Token generated always results in 401 when submitted to Apple servers

I am using the following code in PHP to generate a JWT token to use with the App Store Server API:

$keyId = 'provided by apple';
    $priv_key = <<<EOD
    -----BEGIN PRIVATE KEY-----
    provided by apple
    -----END PRIVATE KEY-----
    EOD;

    $pem_private_key = file_get_contents('AuthKey.pem');

    $private_key = openssl_pkey_get_private($pem_private_key);
    $public_key_pem = openssl_pkey_get_details($private_key)['key'];
    $public_key = openssl_pkey_get_public($public_key_pem);
   
    $headers = [
        "kid"=> $keyId,
        "typ" => 'JWT'
    ];
    $payload = [
        "iss" => "provided by apple",
        "iat"  => time(),
        "exp"  => time() + (60 * 60 * 24 * 7),
        "aud" => "appstoreconnect-v1",
        "bid" => "com.bundle.my"
    ];
    $jwt = JWT::encode($payload, $priv_key, 'ES256', $keyId, $headers); 

This results in a JWT token. However when I try to use it with the Apple Store API, I always get 401 Unauthorized; Unauthenticated.

What am I doing wrong?

Upvotes: 0

Views: 541

Answers (2)

Guo Ying
Guo Ying

Reputation: 1

private function generateJWT($key_id, $issuer_id): string
    {
        date_default_timezone_set('Asia/Shanghai'); // 设置为中国标准时间
        $private_key = <<<EOD
-----BEGIN PRIVATE KEY-----

-----END PRIVATE KEY-----
EOD;

//        $private_key = file_get_contents('/var/www/api/config/AuthKey_84PBGULHBW.p8');
//        // 确保私钥成功加载
//        if (!$private_key) {
//            throw new \Exception('无法加载私钥');
//        }

        // 设置 JWT 头部
        $headers = [
            'alg' => 'ES256',
            'kid' => $key_id,
            'typ' => 'JWT'
        ];

        // 设置 JWT 载荷
        $now = time();
        $payload = [
            'iss' => $issuer_id,
            'iat' => $now,
            'exp' => $now + (15 * 60), // JWT 过期时间设置为 15 分钟后
            'aud' => 'appstoreconnect-v1',
        ];

        // 生成 JWT
        $jwt_token = JWT::encode($payload, $private_key, 'ES256', $key_id, $headers);
//        print_r($jwt_token);die;
        return $jwt_token;
    } 

我也401救命 sos

Upvotes: 0

cesarcarlos
cesarcarlos

Reputation: 1405

The problem was the expiration time as Apple only allows an expiration of max 20 mins.

Changed to time() + 1200.

Upvotes: 1

Related Questions