-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathASDecoder.php
More file actions
81 lines (67 loc) · 2.52 KB
/
ASDecoder.php
File metadata and controls
81 lines (67 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace AppleSignIn;
use AppleSignIn\Vendor\JWK;
use AppleSignIn\Vendor\JWT;
use Exception;
/**
* Decode Sign In with Apple identity token, and produce an ASPayload for
* utilizing in backend auth flows to verify validity of provided user creds.
*
* @package AppleSignIn\ASDecoder
* @author Griffin Ledingham <gcledingham@gmail.com>
* @author Angga Bayu S <anggabs86@gmail.com>
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
* @link https://github.com/GriffinLedingham/php-apple-signin
*/
class ASDecoder {
/**
* Parse a provided Sign In with Apple identity token.
*
* @param string $identityToken
* @return object|null
*/
public static function getAppleSignInPayload(string $identityToken) : ?\AppleSignIn\ASPayload
{
$identityPayload = self::decodeIdentityToken($identityToken);
return new ASPayload($identityPayload);
}
/**
* Decode the Apple encoded JWT using Apple's public key for the signing.
*
* @param string $identityToken
* @return object
*/
public static function decodeIdentityToken(string $identityToken) : \stdClass {
$publicKeyKid = JWT::getPublicKeyKid($identityToken);
$publicKeyData = self::fetchPublicKey($publicKeyKid);
$publicKey = $publicKeyData['publicKey'];
$alg = $publicKeyData['alg'];
$payload = JWT::decode($identityToken, $publicKey, [$alg]);
return $payload;
}
/**
* Fetch Apple's public key from the auth/keys REST API to use to decode
* the Sign In JWT.
*
* @param string $publicKeyKid
* @return array
*/
public static function fetchPublicKey(string $publicKeyKid) : array {
$publicKeys = file_get_contents('https://appleid.apple.com/auth/keys');
$decodedPublicKeys = json_decode($publicKeys, true);
if(!isset($decodedPublicKeys['keys']) || count($decodedPublicKeys['keys']) < 1) {
throw new Exception('Invalid key format.');
}
$kids = array_column($decodedPublicKeys['keys'], 'kid');
$parsedKeyData = $decodedPublicKeys['keys'][array_search($publicKeyKid, $kids)];
$parsedPublicKey= JWK::parseKey($parsedKeyData);
$publicKeyDetails = openssl_pkey_get_details($parsedPublicKey);
if(!isset($publicKeyDetails['key'])) {
throw new Exception('Invalid public key details.');
}
return [
'publicKey' => $publicKeyDetails['key'],
'alg' => $parsedKeyData['alg']
];
}
}