voyager
voyager

Reputation: 5

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

I have an iOS app which implements sign in with Apple.

A private key was generated for this app on developer portal.

For the first our app server receives identity token and authorization code from iOS app. We use firebase/jwt-php library to verify identity token with keys here. After complete we have decoded identity token like this:

header:

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

payload:

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

Also client app send to our app server authorisation code like this:

c6b4d8ec548014979b7b7e0f4d63a173e.0.mrty.2sZAWSjybSC6MU0PQAxaag

And troubles starts... I try to obtain refresh token by authorisation code and client secret. I don't use firebase/jwt-php library to create client secret because I read about openSSL issues here. I've converted my .p8 private key to .pem format to use it for sign.

I got a function to generate signed jwt like this:

/**
 * 
 * @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, '=');
        } 

To convert openSSL sign I use fromDER function from 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;
    }

And finally my call to https://appleid.apple.com/auth/token endpoint looks like this:

$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);

And I always have "invalid_client" answer from the Apple server :( What else could go wrong?

Upvotes: 0

Views: 480

Answers (1)

Merricat
Merricat

Reputation: 2841

off the top of my head, try two things:

  1. add an Accept header: 'Accept: application/x-www-form-urlencoded'
  2. pass your post data not inside another array: http_build_query($send_data)

If I think of more things I'll edit my answer.

Upvotes: 0

Related Questions