24

我正在尝试验证我从重定向 Uri 上的“使用 Apple 登录”服务获得的代码。我使用文档中的信息来创建发布数据并生成“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;

{"error":"invalid_client"}我现在得到来自苹果服务器的响应。我究竟做错了什么?会不会是我生成错误的 JWT 令牌?

4

4 回答 4

7

对我来说,问题是我忘记在 Apple 开发门户的 Service Id 部分下验证我的域。

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

该网站不会自动验证,您必须单击验证按钮并在域旁边打一个绿色勾号以确保。在此之后,我没有更多的invalid_client问题。

在此处输入图像描述

2020.07 更新

随着流程发生变化,您只需将域和通信电子邮件添加到:

Certificates, Identifiers & Profiles > More > Configure

于 2019-08-23T08:48:45.153 回答
2

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

  • 不正确的域验证和无效的 redirect_uri
  • 客户 ID 不正确:您的客户 ID 可能不正确。
  • JWT 编码器工作不正常:可能不支持 ES256 算法?
  • 请求类型:对于/auth/authorize,需要使用x-www-form-urlencode,否则会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 参数
  • 使用复制的code,我https://appleid.apple.com/auth/token 使用 x-www-form-urlencoded 参数发布端点:
    • 代码
    • client_id
    • client_secret
    • 重定向uri
    • grant_type="授权码"

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

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

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

于 2019-12-12T20:02:11.857 回答
1

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

因此解决方案是将 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;
}

可以在这个库中找到。更多细节在这里Apple 登录,使用 PHP 和 openSSL 签署 JWT 进行身份验证

于 2020-01-22T10:16:41.017 回答
1

我做了一个小包来在php中生成苹果客户端密码,基于jwt-framework: https ://github.com/kissdigital-com/apple-sign-in-client-secret-generator

于 2019-11-25T16:11:11.167 回答