forked from thephpleague/oauth2-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOAuthServerException.php
387 lines (333 loc) · 11.4 KB
/
OAuthServerException.php
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php
/**
* @author Alex Bilbie <[email protected]>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
declare(strict_types=1);
namespace League\OAuth2\Server\Exception;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
use function htmlspecialchars;
use function http_build_query;
use function sprintf;
class OAuthServerException extends Exception
{
/**
* @var array<string, string>
*/
private array $payload;
private ServerRequestInterface $serverRequest;
/**
* Throw a new exception.
*/
final public function __construct(string $message, int $code, private string $errorType, private int $httpStatusCode = 400, private ?string $hint = null, private ?string $redirectUri = null, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->payload = [
'error' => $errorType,
'error_description' => $message,
];
if ($hint !== null) {
$this->payload['hint'] = $hint;
}
}
/**
* Returns the current payload.
*
* @return array<string, string>
*/
public function getPayload(): array
{
return $this->payload;
}
/**
* Updates the current payload.
*
* @param array<string, string> $payload
*/
public function setPayload(array $payload): void
{
$this->payload = $payload;
}
/**
* Set the server request that is responsible for generating the exception
*/
public function setServerRequest(ServerRequestInterface $serverRequest): void
{
$this->serverRequest = $serverRequest;
}
/**
* Unsupported grant type error.
*/
public static function unsupportedGrantType(): static
{
$errorMessage = 'The authorization grant type is not supported by the authorization server.';
$hint = 'Check that all required parameters have been provided';
return new static($errorMessage, 2, 'unsupported_grant_type', 400, $hint);
}
/**
* Invalid request error.
*/
public static function invalidRequest(string $parameter, ?string $hint = null, ?Throwable $previous = null): static
{
$errorMessage = 'The request is missing a required parameter, includes an invalid parameter value, ' .
'includes a parameter more than once, or is otherwise malformed.';
$hint = ($hint === null) ? sprintf('Check the `%s` parameter', $parameter) : $hint;
return new static($errorMessage, 3, 'invalid_request', 400, $hint, null, $previous);
}
/**
* Invalid client error.
*/
public static function invalidClient(ServerRequestInterface $serverRequest): static
{
$exception = new static('Client authentication failed', 4, 'invalid_client', 401);
$exception->setServerRequest($serverRequest);
return $exception;
}
/**
* Invalid scope error
*/
public static function invalidScope(string $scope, string|null $redirectUri = null): static
{
$errorMessage = 'The requested scope is invalid, unknown, or malformed';
if ($scope === '') {
$hint = 'Specify a scope in the request or set a default scope';
} else {
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
}
return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri);
}
/**
* Invalid credentials error.
*/
public static function invalidCredentials(): static
{
return new static('The user credentials were incorrect.', 6, 'invalid_grant', 400);
}
/**
* Server error.
*
* @codeCoverageIgnore
*/
public static function serverError(string $hint, ?Throwable $previous = null): static
{
return new static(
'The authorization server encountered an unexpected condition which prevented it from fulfilling'
. ' the request: ' . $hint,
7,
'server_error',
500,
null,
null,
$previous
);
}
/**
* Invalid refresh token.
*/
public static function invalidRefreshToken(?string $hint = null, ?Throwable $previous = null): static
{
return new static('The refresh token is invalid.', 8, 'invalid_grant', 400, $hint, null, $previous);
}
/**
* Access denied.
*/
public static function accessDenied(?string $hint = null, ?string $redirectUri = null, ?Throwable $previous = null): static
{
return new static(
'The resource owner or authorization server denied the request.',
9,
'access_denied',
401,
$hint,
$redirectUri,
$previous
);
}
/**
* Invalid grant.
*/
public static function invalidGrant(string $hint = ''): static
{
return new static(
'The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token '
. 'is invalid, expired, revoked, does not match the redirection URI used in the authorization request, '
. 'or was issued to another client.',
10,
'invalid_grant',
400,
$hint
);
}
public function getErrorType(): string
{
return $this->errorType;
}
/**
* Expired token error.
*
* @param Throwable $previous Previous exception
*
* @return static
*/
public static function expiredToken(?string $hint = null, ?Throwable $previous = null): static
{
$errorMessage = 'The `device_code` has expired and the device ' .
'authorization session has concluded.';
return new static($errorMessage, 11, 'expired_token', 400, $hint, null, $previous);
}
public static function authorizationPending(string $hint = '', ?Throwable $previous = null): static
{
return new static(
'The authorization request is still pending as the end user ' .
'hasn\'t yet completed the user interaction steps. The client ' .
'SHOULD repeat the Access Token Request to the token endpoint',
12,
'authorization_pending',
400,
$hint,
null,
$previous
);
}
/**
* Slow down error used with the Device Authorization Grant.
*
*
* @return static
*/
public static function slowDown(string $hint = '', ?Throwable $previous = null): static
{
return new static(
'The authorization request is still pending and polling should ' .
'continue, but the interval MUST be increased ' .
'by 5 seconds for this and all subsequent requests.',
13,
'slow_down',
400,
$hint,
null,
$previous
);
}
/**
* Unauthorized client error.
*/
public static function unauthorizedClient(?string $hint = null): static
{
return new static(
'The authenticated client is not authorized to use this authorization grant type.',
14,
'unauthorized_client',
400,
$hint
);
}
/**
* Generate a HTTP response.
*/
public function generateHttpResponse(ResponseInterface $response, bool $useFragment = false, int $jsonOptions = 0): ResponseInterface
{
$headers = $this->getHttpHeaders();
$payload = $this->getPayload();
if ($this->redirectUri !== null) {
if ($useFragment === true) {
$this->redirectUri .= (str_contains($this->redirectUri, '#') === false) ? '#' : '&';
} else {
$this->redirectUri .= (str_contains($this->redirectUri, '?') === false) ? '?' : '&';
}
return $response->withStatus(302)->withHeader('Location', $this->redirectUri . http_build_query($payload));
}
foreach ($headers as $header => $content) {
$response = $response->withHeader($header, $content);
}
$jsonEncodedPayload = json_encode($payload, $jsonOptions);
$responseBody = $jsonEncodedPayload === false ? 'JSON encoding of payload failed' : $jsonEncodedPayload;
$response->getBody()->write($responseBody);
return $response->withStatus($this->getHttpStatusCode());
}
/**
* Get all headers that have to be send with the error response.
*
* @return array<string, string> Array with header values
*/
public function getHttpHeaders(): array
{
$headers = [
'Content-type' => 'application/json',
];
// Add "WWW-Authenticate" header
//
// RFC 6749, section 5.2.:
// "If the client attempted to authenticate via the 'Authorization'
// request header field, the authorization server MUST
// respond with an HTTP 401 (Unauthorized) status code and
// include the "WWW-Authenticate" response header field
// matching the authentication scheme used by the client.
if ($this->errorType === 'invalid_client' && $this->requestHasAuthorizationHeader()) {
$authScheme = str_starts_with($this->serverRequest->getHeader('Authorization')[0], 'Bearer') ? 'Bearer' : 'Basic';
$headers['WWW-Authenticate'] = $authScheme . ' realm="OAuth"';
}
return $headers;
}
/**
* Check if the exception has an associated redirect URI.
*
* Returns whether the exception includes a redirect, since
* getHttpStatusCode() doesn't return a 302 when there's a
* redirect enabled. This helps when you want to override local
* error pages but want to let redirects through.
*/
public function hasRedirect(): bool
{
return $this->redirectUri !== null;
}
/**
* Returns the Redirect URI used for redirecting.
*/
public function getRedirectUri(): ?string
{
return $this->redirectUri;
}
/**
* Returns the HTTP status code to send when the exceptions is output.
*/
public function getHttpStatusCode(): int
{
return $this->httpStatusCode;
}
public function getHint(): ?string
{
return $this->hint;
}
/**
* Check if the request has a non-empty 'Authorization' header value.
*
* Returns true if the header is present and not an empty string, false
* otherwise.
*/
private function requestHasAuthorizationHeader(): bool
{
if (!$this->serverRequest->hasHeader('Authorization')) {
return false;
}
$authorizationHeader = $this->serverRequest->getHeader('Authorization');
// Common .htaccess configurations yield an empty string for the
// 'Authorization' header when one is not provided by the client.
// For practical purposes that case should be treated as though the
// header isn't present.
// See https://github.com/thephpleague/oauth2-server/issues/1162
if ($authorizationHeader === [] || $authorizationHeader[0] === '') {
return false;
}
return true;
}
}