]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdConnect/OpenIdConnectIdToken.php
Added token and key handling elements for oidc jwt
[bookstack] / app / Auth / Access / OpenIdConnect / OpenIdConnectIdToken.php
1 <?php
2
3 namespace BookStack\Auth\Access\OpenIdConnect;
4
5 class OpenIdConnectIdToken
6 {
7     /**
8      * @var array
9      */
10     protected $header;
11
12     /**
13      * @var array
14      */
15     protected $payload;
16
17     /**
18      * @var string
19      */
20     protected $signature;
21
22     /**
23      * @var array[]|string[]
24      */
25     protected $keys;
26
27     /**
28      * @var string
29      */
30     protected $issuer;
31
32     /**
33      * @var array
34      */
35     protected $tokenParts = [];
36
37     public function __construct(string $token, string $issuer, array $keys)
38     {
39         $this->keys = $keys;
40         $this->issuer = $issuer;
41         $this->parse($token);
42     }
43
44     /**
45      * Parse the token content into its components.
46      */
47     protected function parse(string $token): void
48     {
49         $this->tokenParts = explode('.', $token);
50         $this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
51         $this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
52         $this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
53     }
54
55     /**
56      * Parse a Base64-JSON encoded token part.
57      * Returns the data as a key-value array or empty array upon error.
58      */
59     protected function parseEncodedTokenPart(string $part): array
60     {
61         $json = $this->base64UrlDecode($part) ?: '{}';
62         $decoded = json_decode($json, true);
63         return is_array($decoded) ? $decoded : [];
64     }
65
66     /**
67      * Base64URL decode. Needs some character conversions to be compatible
68      * with PHP's default base64 handling.
69      */
70     protected function base64UrlDecode(string $encoded): string
71     {
72         return base64_decode(strtr($encoded, '-_', '+/'));
73     }
74
75     /**
76      * Validate all possible parts of the id token.
77      * @throws InvalidTokenException
78      */
79     public function validate()
80     {
81         $this->validateTokenStructure();
82         $this->validateTokenSignature();
83         $this->validateTokenClaims();
84     }
85
86     /**
87      * Validate the structure of the given token and ensure we have the required pieces.
88      * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2
89      * @throws InvalidTokenException
90      */
91     protected function validateTokenStructure(): void
92     {
93         foreach (['header', 'payload'] as $prop) {
94             if (empty($this->$prop) || !is_array($this->$prop)) {
95                 throw new InvalidTokenException("Could not parse out a valid {$prop} within the provided token");
96             }
97         }
98
99         if (empty($this->signature) || !is_string($this->signature)) {
100             throw new InvalidTokenException("Could not parse out a valid signature within the provided token");
101         }
102     }
103
104     /**
105      * Validate the signature of the given token and ensure it validates against the provided key.
106      * @throws InvalidTokenException
107      */
108     protected function validateTokenSignature(): void
109     {
110         if ($this->header['alg'] !== 'RS256') {
111             throw new InvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
112         }
113
114         $parsedKeys = array_map(function($key) {
115             try {
116                 return new JwtSigningKey($key);
117             } catch (InvalidKeyException $e) {
118                 return null;
119             }
120         }, $this->keys);
121
122         $parsedKeys = array_filter($parsedKeys);
123
124         $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
125         foreach ($parsedKeys as $parsedKey) {
126             if ($parsedKey->verify($contentToSign, $this->signature)) {
127                 return;
128             }
129         }
130
131         throw new InvalidTokenException('Token signature could not be validated using the provided keys.');
132     }
133
134     /**
135      * Validate the claims of the token.
136      * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
137      */
138     protected function validateTokenClaims(): void
139     {
140         // TODO
141     }
142
143 }