gpt4 book ai didi

php - 如何验证 "Sign In with Apple"的代码?

转载 作者:可可西里 更新时间:2023-10-31 22:50:39 30 4
gpt4 key购买 nike

我正在尝试验证我从重定向 Uri 上的“使用 Apple 登录”服务获得的代码。我使用了来自 documentation 的信息创建发布数据并生成“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 是我通过开发者账户生成的私钥。 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 token ?

最佳答案

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

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

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

enter image description here

更新2020.07

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

证书、标识符和配置文件>更多>配置

关于php - 如何验证 "Sign In with Apple"的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56459075/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com