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
|
<?php
namespace OAuth\OAuth1\Service;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\OAuth1\Signature\SignatureInterface;
use OAuth\OAuth1\Token\TokenInterface;
use OAuth\OAuth1\Token\StdOAuth1Token;
use OAuth\Common\Service\AbstractService as BaseAbstractService;
abstract class AbstractService extends BaseAbstractService implements ServiceInterface
{
/** @const OAUTH_VERSION */
const OAUTH_VERSION = 1;
/** @var SignatureInterface */
protected $signature;
/** @var UriInterface|null */
protected $baseApiUri;
/**
* {@inheritDoc}
*/
public function __construct(
CredentialsInterface $credentials,
ClientInterface $httpClient,
TokenStorageInterface $storage,
SignatureInterface $signature,
UriInterface $baseApiUri = null
) {
parent::__construct($credentials, $httpClient, $storage);
$this->signature = $signature;
$this->baseApiUri = $baseApiUri;
$this->signature->setHashingAlgorithm($this->getSignatureMethod());
}
/**
* {@inheritDoc}
*/
public function requestRequestToken()
{
$authorizationHeader = array('Authorization' => $this->buildAuthorizationHeaderForTokenRequest());
$headers = array_merge($authorizationHeader, $this->getExtraOAuthHeaders());
$responseBody = $this->httpClient->retrieveResponse($this->getRequestTokenEndpoint(), array(), $headers);
$token = $this->parseRequestTokenResponse($responseBody);
$this->storage->storeAccessToken($this->service(), $token);
return $token;
}
/**
* {@inheritdoc}
*/
public function getAuthorizationUri(array $additionalParameters = array())
{
// Build the url
$url = clone $this->getAuthorizationEndpoint();
foreach ($additionalParameters as $key => $val) {
$url->addToQuery($key, $val);
}
return $url;
}
/**
* {@inheritDoc}
*/
public function requestAccessToken($token, $verifier, $tokenSecret = null)
{
if (is_null($tokenSecret)) {
$storedRequestToken = $this->storage->retrieveAccessToken($this->service());
$tokenSecret = $storedRequestToken->getRequestTokenSecret();
}
$this->signature->setTokenSecret($tokenSecret);
$extraAuthenticationHeaders = array(
'oauth_token' => $token,
);
$bodyParams = array(
'oauth_verifier' => $verifier,
);
$authorizationHeader = array(
'Authorization' => $this->buildAuthorizationHeaderForAPIRequest(
'POST',
$this->getAccessTokenEndpoint(),
$this->storage->retrieveAccessToken($this->service()),
$bodyParams
)
);
$headers = array_merge($authorizationHeader, $this->getExtraOAuthHeaders());
$responseBody = $this->httpClient->retrieveResponse($this->getAccessTokenEndpoint(), $bodyParams, $headers);
$token = $this->parseAccessTokenResponse($responseBody);
$this->storage->storeAccessToken($this->service(), $token);
return $token;
}
/**
* Sends an authenticated API request to the path provided.
* If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used.
*
* @param string|UriInterface $path
* @param string $method HTTP method
* @param array $body Request body if applicable (key/value pairs)
* @param array $extraHeaders Extra headers if applicable.
* These will override service-specific any defaults.
*
* @return string
*/
public function request($path, $method = 'GET', $body = null, array $extraHeaders = array())
{
$uri = $this->determineRequestUriFromPath($path, $this->baseApiUri);
/** @var $token StdOAuth1Token */
$token = $this->storage->retrieveAccessToken($this->service());
$extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders);
$authorizationHeader = array(
'Authorization' => $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $token, $body)
);
$headers = array_merge($authorizationHeader, $extraHeaders);
return $this->httpClient->retrieveResponse($uri, $body, $headers, $method);
}
/**
* Return any additional headers always needed for this service implementation's OAuth calls.
*
* @return array
*/
protected function getExtraOAuthHeaders()
{
return array();
}
/**
* Return any additional headers always needed for this service implementation's API calls.
*
* @return array
*/
protected function getExtraApiHeaders()
{
return array();
}
/**
* Builds the authorization header for getting an access or request token.
*
* @param array $extraParameters
*
* @return string
*/
protected function buildAuthorizationHeaderForTokenRequest(array $extraParameters = array())
{
$parameters = $this->getBasicAuthorizationHeaderInfo();
$parameters = array_merge($parameters, $extraParameters);
$parameters['oauth_signature'] = $this->signature->getSignature(
$this->getRequestTokenEndpoint(),
$parameters,
'POST'
);
$authorizationHeader = 'OAuth ';
$delimiter = '';
foreach ($parameters as $key => $value) {
$authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
$delimiter = ', ';
}
return $authorizationHeader;
}
/**
* Builds the authorization header for an authenticated API request
*
* @param string $method
* @param UriInterface $uri The uri the request is headed
* @param TokenInterface $token
* @param array $bodyParams Request body if applicable (key/value pairs)
*
* @return string
*/
protected function buildAuthorizationHeaderForAPIRequest(
$method,
UriInterface $uri,
TokenInterface $token,
$bodyParams = null
) {
$this->signature->setTokenSecret($token->getAccessTokenSecret());
$parameters = $this->getBasicAuthorizationHeaderInfo();
if (isset($parameters['oauth_callback'])) {
unset($parameters['oauth_callback']);
}
$parameters = array_merge($parameters, array('oauth_token' => $token->getAccessToken()));
$mergedParams = (is_array($bodyParams)) ? array_merge($parameters, $bodyParams) : $parameters;
$parameters['oauth_signature'] = $this->signature->getSignature($uri, $mergedParams, $method);
$authorizationHeader = 'OAuth ';
$delimiter = '';
foreach ($parameters as $key => $value) {
$authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
$delimiter = ', ';
}
return $authorizationHeader;
}
/**
* Builds the authorization header array.
*
* @return array
*/
protected function getBasicAuthorizationHeaderInfo()
{
$dateTime = new \DateTime();
$headerParameters = array(
'oauth_callback' => $this->credentials->getCallbackUrl(),
'oauth_consumer_key' => $this->credentials->getConsumerId(),
'oauth_nonce' => $this->generateNonce(),
'oauth_signature_method' => $this->getSignatureMethod(),
'oauth_timestamp' => $dateTime->format('U'),
'oauth_version' => $this->getVersion(),
);
return $headerParameters;
}
/**
* Pseudo random string generator used to build a unique string to sign each request
*
* @param int $length
*
* @return string
*/
protected function generateNonce($length = 32)
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$nonce = '';
$maxRand = strlen($characters)-1;
for ($i = 0; $i < $length; $i++) {
$nonce.= $characters[rand(0, $maxRand)];
}
return $nonce;
}
/**
* @return string
*/
protected function getSignatureMethod()
{
return 'HMAC-SHA1';
}
/**
* This returns the version used in the authorization header of the requests
*
* @return string
*/
protected function getVersion()
{
return '1.0';
}
/**
* Parses the request token response and returns a TokenInterface.
* This is only needed to verify the `oauth_callback_confirmed` parameter. The actual
* parsing logic is contained in the access token parser.
*
* @abstract
*
* @param string $responseBody
*
* @return TokenInterface
*
* @throws TokenResponseException
*/
abstract protected function parseRequestTokenResponse($responseBody);
/**
* Parses the access token response and returns a TokenInterface.
*
* @abstract
*
* @param string $responseBody
*
* @return TokenInterface
*
* @throws TokenResponseException
*/
abstract protected function parseAccessTokenResponse($responseBody);
}
|