亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Apple 登錄“invalid_client”,使用 PHP 和 openSSL

Apple 登錄“invalid_client”,使用 PHP 和 openSSL

PHP
aluckdog 2022-07-22 09:37:39
我正在嘗試使用此庫將 Apple 登錄實現到 Android 應用程序中。文檔中描述了主要流程:該庫在Android端返回一個授權碼。此授權代碼必須發送到我的后端,然后再將其發送到 Apple 服務器以取回訪問令牌。如這里和這里所述,為了獲得訪問令牌,我們需要向 Apple API 發送參數列表、授權碼和簽名的 JWT。特別是,JWT 需要使用 ES256 算法使用私有 .p8 密鑰進行簽名,該密鑰必須從 Apple 開發人員門戶生成和下載。蘋果文檔這是我的 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    ];問題是蘋果的回應總是:{"error":"invalid_client"}在這里閱讀,似乎問題可能與生成對 Apple 不正確的簽名的 openSSL 有關(“ OpenSSL 的 ES256 簽名結果是 DER 編碼的 ASN.1 結構(它的大小超過 64)。(不是原始 R | | S 值) ”)。有沒有辦法使用 openSSL 獲得正確的簽名?p8 格式是 openssl_sign 和 openssl_pkey_get_private 函數的正確輸入嗎? (我注意到如果在jwt.io中使用提供的 .p8 密鑰來計算簽名的 jwt,則它不起作用。)在 openSSL 文檔中,我讀到應該提供 pem 密鑰,如何將 .p8 轉換為 .pem 密鑰?我還嘗試了一些 PHP 庫,它們基本上使用上述相同的步驟,例如firebase /php-jwt和lcobucci/jwt,但 Apple 的響應仍然是“無效客戶端”。
查看完整描述

1 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

如here所示,問題實際上出在openSSL生成的簽名中。


使用 ES256,數字簽名是兩個無符號整數的串聯,表示為 R 和 S,它們是橢圓曲線 (EC) 算法的結果。R的長度|| S 為 64。


openssl_sign 函數生成一個簽名,該簽名是一個 DER 編碼的 ASN.1 結構(大小 > 64)。


解決方案是將 DER 編碼的簽名轉換為 R 和 S 值的原始串聯。在這個庫中,存在一個函數“ 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 密鑰。從 Apple 開發人員下載的 .p8 密鑰開始,我使用 openSSL 創建了 .pem 密鑰:


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

下面是我的新generateJWT函數代碼,它使用 .pem 密鑰和 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);

    }


查看完整回答
反對 回復 2022-07-22
  • 1 回答
  • 0 關注
  • 504 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號