-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOAuth1Provider.php
296 lines (243 loc) · 9.19 KB
/
OAuth1Provider.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
<?php
/**
* Class OAuth1Provider
*
* @created 09.07.2017
* @author Smiley <smiley@chillerlan.net>
* @copyright 2017 Smiley
* @license MIT
*
* @filesource
*/
declare(strict_types=1);
namespace chillerlan\OAuth\Core;
use chillerlan\HTTP\Utils\{MessageUtil, QueryUtil};
use chillerlan\OAuth\Providers\ProviderException;
use chillerlan\Utilities\Str;
use Psr\Http\Message\{RequestInterface, ResponseInterface, UriInterface};
use function array_merge, hash_hmac, implode, in_array, sprintf, strtoupper, time;
/**
* Implements an abstract OAuth1 (1.0a) provider with all methods required by the OAuth1Interface.
*
* @link https://oauth.net/core/1.0a/
* @link https://datatracker.ietf.org/doc/html/rfc5849
*/
abstract class OAuth1Provider extends OAuthProvider implements OAuth1Interface{
/**
* The request token URL
*/
protected string $requestTokenURL = '';
/**
* @param array<string, scalar>|null $params
*/
public function getAuthorizationURL(array|null $params = null, array|null $scopes = null):UriInterface{
$response = $this->sendRequestTokenRequest($this->requestTokenURL);
$token = $this->parseTokenResponse($response, true);
$params = array_merge(($params ?? []), ['oauth_token' => $token->accessToken]);
return $this->uriFactory->createUri(QueryUtil::merge($this->authorizationURL, $params));
}
/**
* Sends a request to the request token endpoint
*
* @see \chillerlan\OAuth\Core\OAuth1Provider::getAuthorizationURL()
*/
protected function sendRequestTokenRequest(string $url):ResponseInterface{
$params = $this->getRequestTokenRequestParams();
$request = $this->requestFactory
->createRequest('POST', $url)
->withHeader('Authorization', 'OAuth '.QueryUtil::build($params, null, ', ', '"'))
// try to avoid compression
->withHeader('Accept-Encoding', 'identity')
// tumblr requires a content-length header set
->withHeader('Content-Length', '0')
;
foreach($this::HEADERS_AUTH as $header => $value){
$request = $request->withHeader($header, $value);
}
return $this->http->sendRequest($request);
}
/**
* prepares the parameters for the request token request header
*
* @see \chillerlan\OAuth\Core\OAuth1Provider::sendRequestTokenRequest()
* @link https://datatracker.ietf.org/doc/html/rfc5849#section-2.1
*
* @return array<string, scalar>
*/
protected function getRequestTokenRequestParams():array{
$params = [
'oauth_callback' => $this->options->callbackURL,
'oauth_consumer_key' => $this->options->key,
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
];
$params['oauth_signature'] = $this->getSignature($this->requestTokenURL, $params, 'POST');
return $params;
}
/**
* Parses the response from a request to the token endpoint
*
* Note: "oauth_callback_confirmed" is only sent in the request token response
*
* @link https://datatracker.ietf.org/doc/html/rfc5849#section-2.1
* @link https://datatracker.ietf.org/doc/html/rfc5849#section-2.3
* @see \chillerlan\OAuth\Core\OAuth1Provider::getAuthorizationURL()
* @see \chillerlan\OAuth\Core\OAuth1Provider::getAccessToken()
*
* @throws \chillerlan\OAuth\Providers\ProviderException
*/
protected function parseTokenResponse(ResponseInterface $response, bool|null $checkCallbackConfirmed = null):AccessToken{
/** @var array<string, string> $data */
$data = QueryUtil::parse(MessageUtil::decompress($response));
if($data === []){
throw new ProviderException('unable to parse token response');
}
if(isset($data['error'])){
if(in_array($response->getStatusCode(), [400, 401, 403], true)){
throw new UnauthorizedAccessException($data['error']);
}
throw new ProviderException(sprintf('error retrieving access token: "%s"', $data['error']));
}
if(!isset($data['oauth_token']) || !isset($data['oauth_token_secret'])){
throw new ProviderException('invalid token');
}
// MUST be present and set to "true". The parameter is used to differentiate from previous versions of the protocol
if(
$checkCallbackConfirmed === true
&& (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true')
){
throw new ProviderException('invalid OAuth 1.0a response');
}
$token = $this->createAccessToken();
$token->accessToken = $data['oauth_token'];
$token->accessTokenSecret = $data['oauth_token_secret'];
$token->expires = AccessToken::NEVER_EXPIRES;
unset($data['oauth_token'], $data['oauth_token_secret']);
$token->extraParams = $data;
$this->storage->storeAccessToken($token, $this->name);
return $token;
}
/**
* Generates a request signature
*
* @link https://datatracker.ietf.org/doc/html/rfc5849#section-3.4
* @see \chillerlan\OAuth\Core\OAuth1Provider::getRequestTokenRequestParams()
* @see \chillerlan\OAuth\Core\OAuth1Provider::getRequestAuthorization()
*
* @param array<string, scalar> $params
*
* @throws \chillerlan\OAuth\Providers\ProviderException
*/
protected function getSignature(
UriInterface|string $url,
array $params,
string $method,
string|null $accessTokenSecret = null,
):string{
if(!$url instanceof UriInterface){
$url = $this->uriFactory->createUri($url);
}
if($url->getHost() === '' || $url->getScheme() !== 'https'){
throw new ProviderException(sprintf('getSignature: invalid url: "%s"', $url));
}
$signatureParams = array_merge(QueryUtil::parse($url->getQuery()), $params);
$url = $url->withQuery('')->withFragment('');
// make sure we have no unwanted params in the array
unset($signatureParams['oauth_signature']);
// @link https://datatracker.ietf.org/doc/html/rfc5849#section-3.4.1.1
$data = QueryUtil::recursiveRawurlencode([strtoupper($method), (string)$url, QueryUtil::build($signatureParams)]);
// @link https://datatracker.ietf.org/doc/html/rfc5849#section-3.4.2
$key = QueryUtil::recursiveRawurlencode([$this->options->secret, ($accessTokenSecret ?? '')]);
$hash = hash_hmac('sha1', implode('&', $data), implode('&', $key), true);
return Str::base64encode($hash);
}
/**
* @inheritDoc
* @throws \chillerlan\OAuth\Providers\ProviderException
*/
public function getAccessToken(string $requestToken, string $verifier):AccessToken{
$token = $this->storage->getAccessToken($this->name);
if($requestToken !== $token->accessToken){
throw new ProviderException('request token mismatch');
}
$params = $this->getAccessTokenRequestHeaderParams($token, $verifier);
$response = $this->sendAccessTokenRequest($params);
return $this->parseTokenResponse($response);
}
/**
* Prepares the header params for the access token request
*
* @return array<string, scalar>
*/
protected function getAccessTokenRequestHeaderParams(AccessToken $requestToken, string $verifier):array{
/** @var array<string, scalar> $params */
$params = [
'oauth_consumer_key' => $this->options->key,
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $requestToken->accessToken,
'oauth_version' => '1.0',
'oauth_verifier' => $verifier,
];
$params['oauth_signature'] = $this->getSignature(
$this->accessTokenURL,
$params,
'POST',
$requestToken->accessTokenSecret,
);
return $params;
}
/**
* Adds the "Authorization" header to the given `RequestInterface` using the given array or parameters
*
* @param array<string, scalar> $params
*/
protected function setAuthorizationHeader(RequestInterface $request, array $params):RequestInterface{
return $request->withHeader('Authorization', sprintf('OAuth %s', QueryUtil::build($params, null, ', ', '"')));
}
/**
* Sends the access token request
*
* @see \chillerlan\OAuth\Core\OAuth1Provider::getAccessToken()
*
* @param array<string, scalar> $headerParams
*/
protected function sendAccessTokenRequest(array $headerParams):ResponseInterface{
$request = $this->requestFactory
->createRequest('POST', $this->accessTokenURL)
->withHeader('Accept-Encoding', 'identity')
->withHeader('Content-Length', '0')
;
$request = $this->setAuthorizationHeader($request, $headerParams);
return $this->http->sendRequest($request);
}
/**
* @inheritDoc
* @see \chillerlan\OAuth\Core\OAuth1Provider::sendAccessTokenRequest()
*/
public function getRequestAuthorization(RequestInterface $request, AccessToken|null $token = null):RequestInterface{
$token ??= $this->storage->getAccessToken($this->name);
if($token->isExpired()){
throw new InvalidAccessTokenException;
}
/** @var array<string, scalar> $params */
$params = [
'oauth_consumer_key' => $this->options->key,
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $token->accessToken,
'oauth_version' => '1.0',
];
$params['oauth_signature'] = $this->getSignature(
$request->getUri(),
$params,
$request->getMethod(),
$token->accessTokenSecret,
);
return $this->setAuthorizationHeader($request, $params);
}
}