如何验证来自 "Sign In with Apple" 的代码?

How to verify code from "Sign In with Apple"?

我正在尝试验证我从重定向 Uri 上的 "Sign In with Apple" 服务获得的代码。我使用 documentation 中的信息创建了 post 数据并生成了 "client_secret".

我得到的回复是:{"error":"invalid_client"}

我生成 "client_secret" 的函数可以在下面找到:

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

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 = encode(json_encode($header)).'.'.encode(json_encode($body));
    $signature = '';
    $success = openssl_sign($payloads, $signature, $privKey, OPENSSL_ALGO_SHA256);
    if (!$success) return false;

    return $payload.'.'.encode($signature);
}

本例中我的变量:

$kid 是我的私钥标识符。在本例中为 JYJ5GS7N9K。我从这里得到标识符 https://developer.apple.com/account/resources/authkeys/list

$iss 是我的开发者帐户中的团队标识符。在本例中为 WGL33ABCD6。

$sub 与 "client_id" 的值相同。我在这个例子中的 "client_id" 是 "dev.hanashi.sign-in-with-apple"。我从此处的应用程序标识符中获取了客户端 ID:https://developer.apple.com/account/resources/identifiers/list

$key 是我通过开发者账号生成的私钥。密钥的格式如下:

-----BEGIN PRIVATE KEY-----
myrandomgeneratedkeybyappledeveloperaccount
-----END PRIVATE KEY-----

这是发出请求的 php 代码:

$key = <<<EOD
-----BEGIN PRIVATE KEY-----
myrandomgeneratedkeybyappledeveloperaccount
-----END PRIVATE KEY-----
EOD; // replaced with correct key

$kid = 'JYJ5GS7N9K'; // identifier for private key
$iss = 'WGL33ABCD6'; // team identifier
$sub = 'dev.hanashi.sign-in-with-apple'; // my app id

$jwt = generateJWT($kid, $iss, $sub, $key);

$data = [
    'client_id' => $sub,
    'client_secret' => $jwt,
    'code' => $_POST['code'],
    'grant_type' => 'authorization_code',
    'request_uri' => 'https://myurl.tld/redirect.php'
];
$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($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
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);

curl_close ($ch);
echo $serverOutput;

我现在从 Apple 服务器收到响应 {"error":"invalid_client"}。我究竟做错了什么?会不会是我生成的 JWT 令牌有误?

我的问题是我忘记在 Apple 开发门户的服务 ID 部分验证我的域。

您需要下载他们给您的密钥,并将其上传至: https://example.com/.well-known/apple-developer-domain-association.txt

该网站不会自动验证,您必须单击验证按钮并在域旁边看到一个绿色勾号才能确定。在此之后,我再也没有 invalid_client 问题了。

更新2020.07

由于流程已更改,您只需将域和通信电子邮件添加到:

Certificates, Identifiers & Profiles > More > Configure

我在 php 中基于 jwt-framework 制作了一个小包来生成 apple client secret: https://github.com/kissdigital-com/apple-sign-in-client-secret-generator

这个错误我有好几次了。以下是我能找到的原因:

  • 不正确的域验证和无效 redirect_uri
  • 客户 ID 不正确:您的客户 ID 可能不正确。
  • JWT编码器工作不正常:可能不支持ES256算法?
  • 请求类型:对于/auth/authorize,您需要使用x-www-form-url编码,否则会出现invalid_client错误。

当我解决这些问题时,我开始出现 invalid_grant 错误。以下是我一直在执行的步骤:

  • 我通过 JWT
  • 创建了 client_secret
  • 我在网络浏览器上手动导航到 https://appleid.apple.com/auth/authorize?response_type=code&state=abcdefg&client_id=com.company.apple-sign-in-abcd&scope=openid&redirect_uri=https://app.com/redirect_uri
  • 授权
  • 它重定向回后端 url(它给出了 404,因为它还没有部署)。
  • 我在
  • 时复制了url栏中的代码参数
  • 使用复制的 code,我发布了 https://appleid.apple.com/auth/token 带有 x-www-form-url 编码参数的端点:
    • 代码
    • client_id
    • client_secret
    • redirect_uri
    • grant_type="authorization_code"

如果你错过几秒钟,code 就会失效,你会得到 invalid_grant 错误。如果您在几秒钟内立即复制并粘贴,您将收到回复:

{
    "access_token": "abcdefg",
    "token_type": "Bearer",
    "expires_in": 3600,
    "refresh_token": "abcdefg",
    "id_token": "abcdefghijklmnopqrstu"
}

下一步是使用 Apple 的 public 密钥解码 id_token。

{"error":"invalid_client"} 消息可能与 openssl_sign 函数生成的无效签名有关。必须使用 ES256 算法对 JWT 进行签名,生成的签名应该是两个无符号整数的串联,表示为 R 和 S。事实证明 openssl_sign 函数生成 DER 编码的 ASN.1 签名这对 Apple 来说是不正确的(参见 here)。

因此解决方案是将 openSSL 生成的 DER 编码的 ASN.1 签名转换为 R 和 S 值的简单串联。

这可以通过使用以下函数来完成:

/**
 * @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;
}

可以在 this library. More details here

中找到