-
-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathAppCheckTokenVerifier.php
More file actions
89 lines (76 loc) · 2.71 KB
/
AppCheckTokenVerifier.php
File metadata and controls
89 lines (76 loc) · 2.71 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
82
83
84
85
86
87
88
89
<?php
declare(strict_types=1);
namespace Kreait\Firebase\AppCheck;
use Firebase\JWT\CachedKeySet;
use Firebase\JWT\JWT;
use Kreait\Firebase\Exception\AppCheck\FailedToVerifyAppCheckToken;
use Kreait\Firebase\Exception\AppCheck\InvalidAppCheckToken;
use LogicException;
use Throwable;
use function in_array;
use function str_starts_with;
/**
* @internal
*
* @phpstan-import-type DecodedAppCheckTokenShape from DecodedAppCheckToken
*/
final readonly class AppCheckTokenVerifier
{
private const string APP_CHECK_ISSUER_PREFIX = 'https://firebaseappcheck.googleapis.com/';
/**
* @param non-empty-string $projectId
*/
public function __construct(
private string $projectId,
private CachedKeySet $keySet,
) {
}
/**
* Verifies the format and signature of a Firebase App Check token.
*
* @param string $token the Firebase Auth JWT token to verify
*
* @throws FailedToVerifyAppCheckToken if the token could not be verified
* @throws InvalidAppCheckToken if the token is invalid
*/
public function verifyToken(string $token): DecodedAppCheckToken
{
$decodedToken = $this->decodeJwt($token);
$this->verifyContent($decodedToken);
return $decodedToken;
}
/**
* @param string $token the Firebase App Check JWT token to decode
*
* @throws FailedToVerifyAppCheckToken if the token could not be verified
* @throws InvalidAppCheckToken if the token is invalid
*/
private function decodeJwt(string $token): DecodedAppCheckToken
{
try {
/** @var DecodedAppCheckTokenShape $payload */
$payload = (array) JWT::decode($token, $this->keySet);
} catch (LogicException $e) {
throw new InvalidAppCheckToken(message: $e->getMessage(), previous: $e);
} catch (Throwable $e) {
throw new FailedToVerifyAppCheckToken(message: $e->getMessage(), previous: $e);
}
return DecodedAppCheckToken::fromArray($payload);
}
/**
* Verifies the content of a Firebase App Check JWT.
*
* @param DecodedAppCheckToken $token the decoded Firebase App Check token to verify
*
* @throws FailedToVerifyAppCheckToken if the token could not be verified
*/
private function verifyContent(DecodedAppCheckToken $token): void
{
if (!in_array('projects/'.$this->projectId, $token->aud, true)) {
throw new FailedToVerifyAppCheckToken('The "aud" claim must include the project ID.');
}
if (!str_starts_with($token->iss, self::APP_CHECK_ISSUER_PREFIX)) {
throw new FailedToVerifyAppCheckToken('The provided App Check token has incorrect "iss" (issuer) claim.');
}
}
}