-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathAbstractOauth2Action.class.php
More file actions
292 lines (249 loc) · 8.78 KB
/
AbstractOauth2Action.class.php
File metadata and controls
292 lines (249 loc) · 8.78 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
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
<?php
namespace wcf\action;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Psr7\Request;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Diactoros\Uri;
use ParagonIE\ConstantTime\Base64UrlSafe;
use ParagonIE\ConstantTime\Hex;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use wcf\system\exception\NamedUserException;
use wcf\system\exception\PermissionDeniedException;
use wcf\system\io\HttpFactory;
use wcf\system\user\authentication\oauth\exception\StateValidationException;
use wcf\system\user\authentication\oauth\User as OauthUser;
use wcf\system\WCF;
use wcf\util\HtmlString;
use wcf\util\JSON;
/**
* Generic implementation to handle the OAuth 2 flow.
*
* @author Tim Duesterhus
* @copyright 2001-2022 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @since 5.4
* @deprecated 6.1 use `AbstractOauth2AuthAction` instead
*/
abstract class AbstractOauth2Action extends AbstractAction
{
private const STATE = self::class . "\0state_parameter";
private const PKCE = self::class . "\0pkce";
private ClientInterface $httpClient;
/**
* @inheritDoc
*/
public function readParameters()
{
parent::readParameters();
if (WCF::getSession()->spiderIdentifier) {
throw new PermissionDeniedException();
}
}
/**
* Returns a "static" instance of the HTTP client to use to allow
* for TCP connection reuse.
*/
protected function getHttpClient(): ClientInterface
{
if (!isset($this->httpClient)) {
$this->httpClient = HttpFactory::makeClientWithTimeout(5);
}
return $this->httpClient;
}
/**
* Returns the URL of the '/token' endpoint that turns the code into an access token.
*/
abstract protected function getTokenEndpoint(): string;
/**
* Returns the 'client_id'.
*/
abstract protected function getClientId(): string;
/**
* Returns the 'client_secret'.
*/
abstract protected function getClientSecret(): string;
/**
* Returns the 'scope' to request.
*/
abstract protected function getScope(): string;
/**
* Returns the URL of the '/authorize' endpoint where the user is redirected to.
*/
abstract protected function getAuthorizeUrl(): string;
/**
* Returns the callback URL. This should most likely be:
*
* LinkHandler::getInstance()->getControllerLink(self::class)
*/
abstract protected function getCallbackUrl(): string;
/**
* Whether to validate the state or not. Should be 'true' to protect
* against CSRF attacks.
*/
abstract protected function supportsState(): bool;
/**
* Whether to use PKCE (RFC 7636). Defaults to 'false'.
*/
protected function usePkce(): bool
{
return false;
}
/**
* Turns the access token response into an oauth user.
*
* @param array<string, string> $accessToken
*/
abstract protected function getUser(array $accessToken): OauthUser;
/**
* Processes the user (e.g. by registering session variables and redirecting somewhere).
*/
abstract protected function processUser(OauthUser $oauthUser): ResponseInterface;
/**
* Validates the state parameter.
*
* @return void
*/
protected function validateState()
{
try {
if (!isset($_GET['state'])) {
throw new StateValidationException('Missing state parameter');
}
if (!($sessionState = WCF::getSession()->getVar(self::STATE))) {
throw new StateValidationException('Missing state in session');
}
if (!\hash_equals($sessionState, (string)$_GET['state'])) {
throw new StateValidationException('Mismatching state');
}
} finally {
WCF::getSession()->unregister(self::STATE);
}
}
/**
* Turns the 'code' into an access token.
*
* @return mixed[]
*/
protected function codeToAccessToken(string $code): array
{
$payload = [
'grant_type' => 'authorization_code',
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'redirect_uri' => $this->getCallbackUrl(),
'code' => $code,
];
if ($this->usePkce()) {
if (!($verifier = WCF::getSession()->getVar(self::PKCE))) {
throw new StateValidationException('Missing PKCE verifier in session');
}
$payload['code_verifier'] = $verifier;
}
$request = new Request('POST', $this->getTokenEndpoint(), [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
], \http_build_query($payload, '', '&', \PHP_QUERY_RFC1738));
try {
$response = $this->getHttpClient()->send($request);
} finally {
// Validate state. Validation of state is executed after fetching the
// access_token to invalidate 'code'.
//
// Validation is happening within the `finally` so that the StateValidationException
// overwrites any HTTP exception (improving the error message).
if ($this->supportsState()) {
$this->validateState();
}
}
$parsed = JSON::decode((string)$response->getBody());
if (!empty($parsed['error'])) {
throw new \Exception(\sprintf(
"Access token response indicates an error: '%s'",
$parsed['error']
));
}
if (empty($parsed['access_token'])) {
throw new \Exception("Access token response does not have the 'access_token' key.");
}
return $parsed;
}
protected function handleError(string $error): ResponseInterface
{
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable('wcf.user.3rdparty.login.error.' . $error)
));
}
/**
* Initiates the OAuth flow by redirecting to the '/authorize' URL.
*/
protected function initiate(): ResponseInterface
{
$parameters = [
'response_type' => 'code',
'client_id' => $this->getClientId(),
'scope' => $this->getScope(),
'redirect_uri' => $this->getCallbackUrl(),
];
if ($this->supportsState()) {
$token = Hex::encode(\random_bytes(16));
WCF::getSession()->register(self::STATE, $token);
$parameters['state'] = $token;
}
if ($this->usePkce()) {
$verifier = Hex::encode(\random_bytes(32));
WCF::getSession()->register(self::PKCE, $verifier);
$parameters['code_challenge'] = Base64UrlSafe::encodeUnpadded(\hash('sha256', $verifier, true));
$parameters['code_challenge_method'] = 'S256';
}
$encodedParameters = \http_build_query($parameters, '', '&');
$url = new Uri($this->getAuthorizeUrl());
$query = $url->getQuery();
if ($query !== '') {
$url = $url->withQuery("{$query}&{$encodedParameters}");
} else {
$url = $url->withQuery($encodedParameters);
}
return new RedirectResponse($url);
}
/**
* @inheritDoc
*/
public function execute()
{
parent::execute();
try {
if (isset($_GET['code'])) {
$accessToken = $this->codeToAccessToken($_GET['code']);
$oauthUser = $this->getUser($accessToken);
return $this->processUser($oauthUser);
} elseif (isset($_GET['error'])) {
return $this->handleError($_GET['error']);
} else {
return $this->initiate();
}
} catch (NamedUserException | PermissionDeniedException $e) {
throw $e;
} catch (StateValidationException $e) {
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable(
'wcf.user.3rdparty.login.error.stateValidation'
)
));
} catch (\Exception $e) {
$exceptionID = \wcf\functions\exception\logThrowable($e);
$type = 'genericException';
if ($e instanceof ClientExceptionInterface) {
$type = 'httpError';
}
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable(
'wcf.user.3rdparty.login.error.' . $type,
[
'exceptionID' => $exceptionID,
]
)
));
}
}
}