php - Apple Sign In "invalid_client",使用 PHP 和 openSSL 签署 JWT 进行身份验证

标签 php android openssl jwt apple-sign-in

我正在尝试使用此 library 将 Apple 登录到 Android 应用程序中。文档中描述了主要流程:库在Android端返回一个授权码。该授权代码必须发送到我的后端,而后端又将其发送到 Apple 服务器以便取回访问 token 。

如上所述herehere ,为了获取访问 token ,我们需要向 Apple API 发送参数列表、授权代码和签名的 JWT。特别是,JWT 需要使用私有(private) .p8 key 通过 ES256 算法进行签名,该 key 必须从 Apple 开发者门户生成和下载。 Apple doc

这是我的 PHP 脚本:

<?php

$authorization_code = $_POST('auth_code');

$privateKey = <<<EOD
-----BEGIN PRIVATE KEY-----
my_private_key_downloaded_from_apple_developer_portal (.p8 format)
-----END PRIVATE KEY-----
EOD;

$kid = 'key_id_of_the_private_key'; //Generated in Apple developer Portal
$iss = 'team_id_of_my_developer_profile';
$client_id = 'identifier_setted_in_developer_portal'; //Generated in Apple developer Portal

$signed_jwt = $this->generateJWT($kid, $iss, $client_id, $privateKey);

$data = [
            'client_id' => $client_id,
            'client_secret' => $signed_jwt,
            'code' => $authorization_code,
            'grant_type' => 'authorization_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, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$serverOutput = curl_exec($ch);

curl_close ($ch);

var_dump($serverOutput);

function generateJWT($kid, $iss, $sub, $key) {

    $header = [
        'alg' => 'ES256',
        'kid' => $kid
    ];
    $body = [
        'iss' => $iss,
        'iat' => time(),
        'exp' => time() + 3600,
        'aud' => 'https://appleid.apple.com',
        'sub' => $sub
    ];

    $privKey = openssl_pkey_get_private($key);
    if (!$privKey) return false;

    $payload = $this->encode(json_encode($header)).'.'.$this->encode(json_encode($body));
    $signature = '';
    $success = openssl_sign($payload, $signature, $privKey, OPENSSL_ALGO_SHA256);
    if (!$success) return false;

    return $payload.'.'.$this->encode($signature);
}

function encode($data) {
    $encoded = strtr(base64_encode($data), '+/', '-_');
    return rtrim($encoded, '=');
}

?>

问题是苹果的回应总是:

{"error":"invalid_client"}

阅读here看来问题可能与 openSSL 相关,它生成的签名对于 Apple 来说不正确(“OpenSSL 的 ES256 签名结果是 DER 编码的 ASN.1 结构(其大小超过 64)。(不是原始 R || S 值)")。

有没有办法使用openSSL获得正确的签名?

p8 格式是 openssl_sign 和 openssl_pkey_get_private 函数的正确输入吗? (我注意到,如果在 jwt.io 中使用提供的 .p8 key 来计算签名的 jwt,则该 key 不起作用。)

在 openSSL 文档中,我读到应提供 pem key ,如何将 .p8 转换为 .pem key ?

我还尝试了一些 PHP 库,它们基本上使用与上述相同的步骤,例如 firebase/php-jwtlcobucci/jwt但苹果的回应仍然是“无效客户端”。

预先感谢您的帮助,

编辑

我试图从等式中完全删除 openSSL。使用从 .p8 生成的 .pem key ,我使用 jwt.io 生成了一个签名的 JWT。通过此签名的 JWT,Apple API 可以正确回复。此时我几乎可以肯定这是一个 openSSL 签名问题。关键问题是如何使用PHP和openSSL获得正确的ES256签名。

最佳答案

如图所示here ,问题实际上出在openSSL生成的签名上。

使用 ES256,数字签名是两个无符号整数的串联,表示为 R 和 S,它们是椭圆曲线 (EC) 算法的结果。 R 的长度 || S 为 64。

openssl_sign 函数生成一个签名,该签名是 DER 编码的 ASN.1 结构(大小 > 64)。

解决方案是将 DER 编码的签名转换为 R 和 S 值的原始串联。在 this library存在执行此类转换的函数“fromDER”:

    /**
     * @param string $der
     * @param int    $partLength
     *
     * @return string
     */
    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 preparePositiveInteger(string $data)
    {
        if (mb_substr($data, 0, 2, '8bit') > '7f') {
            return '00'.$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;
    }
    /**
     * @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;
    }

另一点是应向 open_ssl_sign 函数提供 .pem key 。从从 Apple 开发人员下载的 .p8 key 开始,我使用 openSSL 创建了 .pem key :

openssl pkcs8 -in AuthKey_KEY_ID.p8 -nocrypt -out AuthKey_KEY_ID.pem

下面是我的新 generateJWT 函数代码,它使用 .pem key 和 fromDER 函数来转换 openSSL 生成的签名:

    function generateJWT($kid, $iss, $sub) {
        
        $header = [
            'alg' => 'ES256',
            'kid' => $kid
        ];
        $body = [
            'iss' => $iss,
            'iat' => time(),
            'exp' => time() + 3600,
            'aud' => 'https://appleid.apple.com',
            'sub' => $sub
        ];

        $privKey = openssl_pkey_get_private(file_get_contents('AuthKey_.pem'));
        if (!$privKey){
           return false;
        }

        $payload = $this->encode(json_encode($header)).'.'.$this->encode(json_encode($body));
        
        $signature = '';
        $success = openssl_sign($payload, $signature, $privKey, OPENSSL_ALGO_SHA256);
        if (!$success) return false;

        $raw_signature = $this->fromDER($signature, 64);
        
        return $payload.'.'.$this->encode($raw_signature);
    }

希望对你有帮助

关于php - Apple Sign In "invalid_client",使用 PHP 和 openSSL 签署 JWT 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737488/

相关文章:

php - .htaccess 1and1.com Codeigniter

java - 下载数据时 UI-Thread 似乎滞后

cryptography - OpenSSL GCM 解密中的后期身份验证

c++ - 将 STACK_OF(X509) 转换为 ASN1 流

python-3.x - 如何使 SSL 在 pip3 中工作?

php - 如果行状态为 1 个使用 CodeIgniter 在 View 上批准的输出

窗口提交方法内的Javascript停止工作

php - 使用 DAV 协议(protocol)在 PHP 中上传文件

Android ActionMode 标题背景色

android - 触发几个高优先级通知后 Firebase 推送通知延迟