Anonymous
Сообщение: проверка Apple не удалась, ошибка: `{error:valid_client}` в Laravel PHP
Сообщение
Anonymous » 08 ноя 2024, 03:20
Я пытаюсь подтвердить вход в Apple в своем проекте Laravel, но обнаружил ошибку. Может ли кто-нибудь мне помочь? Я даже включил скриншоты идентификатора ключа и идентификатора службы (с измененной конфиденциальной информацией).
{успех: false, сообщение: не удалось проверить Apple, ошибка: {ошибка: инвалид_клиент }}
мой файл .env
Код: Выделить всё
APPLE_CLIENT_ID=com.example.apple
APPLE_TEAM_ID=NR88888888
APPLE_KEY_ID=RJ85222222
Вот моя функция (мне пришлось обрезать некоторые части, потому что StackOverflow не позволяет опубликовать всю функцию).
function loginWithApple(Request $request )
{
try
{
$authCode = $request->input('apple_authorization_code');
if (empty($authCode))
{
return response()->json([
'success' => false,
'message' => 'Требуется код авторизации'
], 400);
Код: Выделить всё
// Load and validate private key file
$path = storage_path('appleKeys/applePrivateKey/AuthKey_RJ85222222.p8');
if (!file_exists($path))
{
Log::error('Apple Login: Private key file not found', ['path' => $path]);
throw new \Exception('Apple private key file not found at: ' . $path);
}
$privateKeyContent = file_get_contents($path);
if (!$privateKeyContent)
{
Log::error('Apple Login: Failed to read private key file');
throw new \Exception('Failed to read private key file');
}
// Ensure private key format
$privateKey = openssl_pkey_get_private($privateKeyContent);
if (!$privateKey)
{
Log::error('Apple Login: Invalid private key format', [
'openssl_error' => openssl_error_string()
]);
throw new \Exception('Invalid private key format: ' . openssl_error_string());
}
// Generate client secret (JWT)
$timestamp = time();
$header = [
'alg' => 'ES256',
'kid' => env('APPLE_KEY_ID')
];
$payload = [
'iss' => env('APPLE_TEAM_ID'),
'iat' => $timestamp,
'exp' => $timestamp + 86400 * 180, // 180 days
'aud' => 'https://appleid.apple.com',
'sub' => env('APPLE_CLIENT_ID'),
];
// Base64Url encode header and payload
$base64Header = rtrim(strtr(base64_encode(json_encode($header)), '+/', '-_'), '=');
$base64Payload = rtrim(strtr(base64_encode(json_encode($payload)), '+/', '-_'), '=');
// Create signature
$signature = '';
if (!openssl_sign(
$base64Header . '.' . $base64Payload,
$signature,
$privateKey,
OPENSSL_ALGO_SHA256
)) {
Log::error('Apple Login: Failed to create signature', [
'openssl_error' => openssl_error_string()
]);
throw new \Exception('Failed to create signature: ' . openssl_error_string());
}
$base64Signature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');
$clientSecret = $base64Header . '.' . $base64Payload . '.' . $base64Signature;
// Send request to Apple for token
$requestData = [
'client_id' => env('APPLE_CLIENT_ID'),
'client_secret' => $clientSecret,
'code' => $authCode,
'grant_type' => 'authorization_code'
];
Log::debug('Apple Login: Sending request to Apple', [
'url' => 'https://appleid.apple.com/auth/token',
'client_id' => env('APPLE_CLIENT_ID'),
'code' => $authCode,
'code_length' => strlen($authCode),
]);
// $response = Http::asForm()->post('https://appleid.apple.com/auth/token', $requestData);
$response = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded'
])->post('https://appleid.apple.com/auth/token', $requestData);
if (!$response->successful())
{
Log::error('Apple Login: Failed response from Apple', [
'status' => $response->status(),
'error' => $response->json(),
]);
return response()->json([
'success' => false,
'message' => 'Failed to verify with Apple',
'error' => $response->json()
], 400);
}
$data = $response->json();
$idToken = $data['id_token'];
$tokenParts = explode('.', $idToken);
if (count($tokenParts) != 3) {
return response()->json([
'success' => false,
'message' => 'Invalid token format'
], 400);
}
}
catch (\Exception $e)
{
Log::error('Apple Sign In Error', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
}
Подробнее здесь:
https://stackoverflow.com/questions/791 ... ent-in-lar
1731025220
Anonymous
Я пытаюсь подтвердить вход в Apple в своем проекте Laravel, но обнаружил ошибку. Может ли кто-нибудь мне помочь? Я даже включил скриншоты идентификатора ключа и идентификатора службы (с измененной конфиденциальной информацией). {успех: false, сообщение: не удалось проверить Apple, ошибка: {ошибка: инвалид_клиент }} мой файл .env [code]APPLE_CLIENT_ID=com.example.apple APPLE_TEAM_ID=NR88888888 APPLE_KEY_ID=RJ85222222 [/code] Вот моя функция (мне пришлось обрезать некоторые части, потому что StackOverflow не позволяет опубликовать всю функцию). function loginWithApple(Request $request ) { try { $authCode = $request->input('apple_authorization_code'); if (empty($authCode)) { return response()->json([ 'success' => false, 'message' => 'Требуется код авторизации' ], 400); [code] // Load and validate private key file $path = storage_path('appleKeys/applePrivateKey/AuthKey_RJ85222222.p8'); if (!file_exists($path)) { Log::error('Apple Login: Private key file not found', ['path' => $path]); throw new \Exception('Apple private key file not found at: ' . $path); } $privateKeyContent = file_get_contents($path); if (!$privateKeyContent) { Log::error('Apple Login: Failed to read private key file'); throw new \Exception('Failed to read private key file'); } // Ensure private key format $privateKey = openssl_pkey_get_private($privateKeyContent); if (!$privateKey) { Log::error('Apple Login: Invalid private key format', [ 'openssl_error' => openssl_error_string() ]); throw new \Exception('Invalid private key format: ' . openssl_error_string()); } // Generate client secret (JWT) $timestamp = time(); $header = [ 'alg' => 'ES256', 'kid' => env('APPLE_KEY_ID') ]; $payload = [ 'iss' => env('APPLE_TEAM_ID'), 'iat' => $timestamp, 'exp' => $timestamp + 86400 * 180, // 180 days 'aud' => 'https://appleid.apple.com', 'sub' => env('APPLE_CLIENT_ID'), ]; // Base64Url encode header and payload $base64Header = rtrim(strtr(base64_encode(json_encode($header)), '+/', '-_'), '='); $base64Payload = rtrim(strtr(base64_encode(json_encode($payload)), '+/', '-_'), '='); // Create signature $signature = ''; if (!openssl_sign( $base64Header . '.' . $base64Payload, $signature, $privateKey, OPENSSL_ALGO_SHA256 )) { Log::error('Apple Login: Failed to create signature', [ 'openssl_error' => openssl_error_string() ]); throw new \Exception('Failed to create signature: ' . openssl_error_string()); } $base64Signature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '='); $clientSecret = $base64Header . '.' . $base64Payload . '.' . $base64Signature; // Send request to Apple for token $requestData = [ 'client_id' => env('APPLE_CLIENT_ID'), 'client_secret' => $clientSecret, 'code' => $authCode, 'grant_type' => 'authorization_code' ]; Log::debug('Apple Login: Sending request to Apple', [ 'url' => 'https://appleid.apple.com/auth/token', 'client_id' => env('APPLE_CLIENT_ID'), 'code' => $authCode, 'code_length' => strlen($authCode), ]); // $response = Http::asForm()->post('https://appleid.apple.com/auth/token', $requestData); $response = Http::withHeaders([ 'Content-Type' => 'application/x-www-form-urlencoded' ])->post('https://appleid.apple.com/auth/token', $requestData); if (!$response->successful()) { Log::error('Apple Login: Failed response from Apple', [ 'status' => $response->status(), 'error' => $response->json(), ]); return response()->json([ 'success' => false, 'message' => 'Failed to verify with Apple', 'error' => $response->json() ], 400); } $data = $response->json(); $idToken = $data['id_token']; $tokenParts = explode('.', $idToken); if (count($tokenParts) != 3) { return response()->json([ 'success' => false, 'message' => 'Invalid token format' ], 400); } } catch (\Exception $e) { Log::error('Apple Sign In Error', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } [/code] [img]https://i.sstatic.net/6HRq2pBM.jpg[/img] [img]https://i.sstatic.net/ThWxa9Jj.jpg[/img] Подробнее здесь: [url]https://stackoverflow.com/questions/79164085/message-verification-with-apple-failed-error-error-invalid-client-in-lar[/url]