在 "sign with apple" 实施期间尝试通过授权代码获取刷新令牌时总是出现 "invalid_client" 错误

Always occurs "invalid_client" error trying to get refresh token by authorisation code during "sign with apple" implementation

我有一个 iOS 应用程序,它实现了使用 Apple 登录。

已在开发者门户上为此应用生成私钥。

首先,我们的应用程序服务器从 iOS 应用程序接收身份令牌和授权码。我们在这里使用 firebase/jwt-php 库通过密钥验证身份令牌。完成后,我们已经像这样解码了身份​​令牌:

header:

{
    "kid": "eXaunmL",
    "alg": "RS256"
}

有效载荷:

{
    "iss": "https://appleid.apple.com",
    "aud": "com.mycompany.myapp",
    "exp": 1597336478,
    "iat": 1597335878,
    "sub": "000138.77a8b51895c943dcbe1ae4c34721a4c3.1312",
    "nonce": "1597335873132",
    "c_hash": "llDP9yFq6YOQEoi4qDzfDA",
    "email": "useremail@gmail.com",
    "email_verified": "true",
    "auth_time": 1597335878,
    "nonce_supported": true
}

客户端应用程序也会像这样向我们的应用程序服务器发送授权码:

c6b4d8ec548014979b7b7e0f4d63a173e.0.mrty.2sZAWSjybSC6MU0PQAxaag

麻烦开始了…… 我尝试通过授权码和客户端密码获取刷新令牌。我没有使用 firebase/jwt-php 库来创建客户端密钥,因为我读到了有关 openSSL 的问题 。 我已将我的 .p8 私钥转换为 .pem 格式以用于签名。

我有一个函数可以像这样生成签名的 jwt:

/**
 * 
 * @param string $kid 10 digits key ID for my app from developer portal
 * @param string $iss my 10 digits team ID from developer portal
 * @param string $sub com.mycoopany.myapp
 * @return string signed JWT
 */
public static function generateJWT($kid, $iss, $sub) {
                $header = [
                        'alg' => 'ES256',
                        'kid' => $kid
                ];
                $body = [
                        'iss' => $iss,
                        'iat' => time(),
                        'exp' => time() + 600,
                        'aud' => 'https://appleid.apple.com',
                        'sub' => $sub
                ];
                $private_key = <<<EOD
-----BEGIN PRIVATE KEY-----
My private key converted from .p8 to .pem by command:
openssl pkcs8 -in key.p8 -nocrypt -out key.pem
-----END PRIVATE KEY-----
EOD;
                
                $privKey = openssl_pkey_get_private($private_key);
                if (!$privKey){
                     return false;
                }
                $payload = self::encode(json_encode($header,JSON_UNESCAPED_SLASHES)).'.'.self::encode(json_encode($body,JSON_UNESCAPED_SLASHES));
                $signature = '';
                $success = openssl_sign($payload, $signature, $privKey, OPENSSL_ALGO_SHA256);
                if (!$success) return false;
                $raw_signature = self::fromDER($signature, 64);
                return $payload.'.'.self::encode($raw_signature);
        }
        private static function encode($data) {
                $encoded = strtr(base64_encode($data), '+/', '-_');
                return rtrim($encoded, '=');
        } 

要转换 openSSL 符号,我使用 fromDER 函数 this library:

    public static function fromDER(string $der, int $partLength)
    {
        $hex = unpack('H*', $der)[1];
        if ('30' !== mb_substr($hex, 0, 2, '8bit')) { // SEQUENCE
            throw new \RuntimeException();
        }
        if ('81' === mb_substr($hex, 2, 2, '8bit')) { // LENGTH > 128
            $hex = mb_substr($hex, 6, null, '8bit');
        } else {
            $hex = mb_substr($hex, 4, null, '8bit');
        }
        if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER
            throw new \RuntimeException();
        }
        $Rl = hexdec(mb_substr($hex, 2, 2, '8bit'));
        $R = self::retrievePositiveInteger(mb_substr($hex, 4, $Rl * 2, '8bit'));
        $R = str_pad($R, $partLength, '0', STR_PAD_LEFT);
        $hex = mb_substr($hex, 4 + $Rl * 2, null, '8bit');
        if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER
            throw new \RuntimeException();
        }
        $Sl = hexdec(mb_substr($hex, 2, 2, '8bit'));
        $S = self::retrievePositiveInteger(mb_substr($hex, 4, $Sl * 2, '8bit'));
        $S = str_pad($S, $partLength, '0', STR_PAD_LEFT);
        return pack('H*', $R.$S);
    }
    
    /**
     * @param string $data
     *
     * @return string
     */
    private static function retrievePositiveInteger(string $data)
    {
        while ('00' === mb_substr($data, 0, 2, '8bit') && mb_substr($data, 2, 2, '8bit') > '7f') {
            $data = mb_substr($data, 2, null, '8bit');
        }
        return $data;
    }

最后我对 https://appleid.apple.com/auth/token 端点的调用如下所示:

$signed_jwt = opensslFix::generateJWT($my_kid, 'myTeamID', $app);
$send_data = [
    'client_id' => $app,
    'client_secret' => $signed_jwt,
    'grant_type' => 'authorization_code',
    'code' => $request->code
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://appleid.apple.com/auth/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([$send_data]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6');

$serverOutput = curl_exec($ch);

我总是从 Apple 服务器得到“invalid_client”答案:( 还有什么可能出错?

在我的脑海中,尝试两件事:

  1. 添加接受 header:'Accept: application/x-www-form-urlencoded'
  2. 传递不在另一个数组中的 post 数据:http_build_query($send_data)

如果我想到更多的东西,我会编辑我的答案。