Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
OauthClient.php
Go to the documentation of this file.
1 <?php
9 
11 use OAuth\Common\Consumer\Credentials;
12 use OAuth\Common\Http\Client\ClientInterface;
13 use OAuth\Common\Http\Exception\TokenResponseException;
14 use OAuth\Common\Http\Uri\Uri;
15 use OAuth\Common\Http\Uri\UriInterface;
16 use OAuth\Common\Storage\TokenStorageInterface;
17 use OAuth\OAuth1\Service\AbstractService;
18 use OAuth\OAuth1\Signature\SignatureInterface;
19 use OAuth\OAuth1\Token\StdOAuth1Token;
20 use OAuth\OAuth1\Token\TokenInterface;
21 
25 class OauthClient extends AbstractService
26 {
30  const DEFAULT_TIMEOUT = 120;
31 
33  protected $_oauthVerifier = null;
34 
35  public function __construct(
36  Credentials $credentials,
37  ClientInterface $httpClient = null,
38  TokenStorageInterface $storage = null,
39  SignatureInterface $signature = null,
40  UriInterface $baseApiUri = null
41  ) {
42  if (!isset($httpClient)) {
43  $httpClient = new \Magento\TestFramework\Authentication\Rest\CurlClient();
44  $httpClient->setTimeout(self::DEFAULT_TIMEOUT);
45  }
46  if (!isset($storage)) {
47  $storage = new \OAuth\Common\Storage\Memory();
48  }
49  if (!isset($signature)) {
50  $signature = new \Magento\TestFramework\Authentication\Rest\OauthClient\Signature($credentials);
51  }
52  parent::__construct($credentials, $httpClient, $storage, $signature, $baseApiUri);
53  }
54 
58  public function getRequestTokenEndpoint()
59  {
60  return new Uri(TESTS_BASE_URL . '/oauth/token/request');
61  }
62 
68  public function getAuthorizationEndpoint()
69  {
70  throw new \OAuth\Common\Exception\Exception(
71  'Magento REST API is 2-legged. Current operation is not available.'
72  );
73  }
74 
80  public function getAccessTokenEndpoint()
81  {
82  return new Uri(TESTS_BASE_URL . '/oauth/token/access');
83  }
84 
90  public function getTestApiEndpoint()
91  {
92  $defaultStoreCode = Bootstrap::getObjectManager()->get(\Magento\Store\Model\StoreManagerInterface::class)
93  ->getStore()->getCode();
94  return new Uri(TESTS_BASE_URL . '/rest/' . $defaultStoreCode . '/V1/testmodule1');
95  }
96 
103  protected function parseAccessTokenResponse($responseBody)
104  {
105  return $this->_parseToken($responseBody);
106  }
107 
115  protected function parseRequestTokenResponse($responseBody)
116  {
117  $data = $this->_parseResponseBody($responseBody);
118  if (isset($data['oauth_verifier'])) {
119  $this->_oauthVerifier = $data['oauth_verifier'];
120  }
121  return $this->_parseToken($responseBody);
122  }
123 
131  protected function _parseToken($responseBody)
132  {
133  $data = $this->_parseResponseBody($responseBody);
134  $token = new StdOAuth1Token();
135  $token->setRequestToken($data['oauth_token']);
136  $token->setRequestTokenSecret($data['oauth_token_secret']);
137  $token->setAccessToken($data['oauth_token']);
138  $token->setAccessTokenSecret($data['oauth_token_secret']);
139  $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
140  unset($data['oauth_token'], $data['oauth_token_secret']);
141  $token->setExtraParams($data);
142  return $token;
143  }
144 
152  protected function _parseResponseBody($responseBody)
153  {
154  if (!is_string($responseBody)) {
155  throw new TokenResponseException("Response body is expected to be a string.");
156  }
157  parse_str($responseBody, $data);
158  if (null === $data || !is_array($data)) {
159  throw new TokenResponseException('Unable to parse response.');
160  } elseif (isset($data['error'])) {
161  throw new TokenResponseException("Error occurred: '{$data['error']}'");
162  }
163  return $data;
164  }
165 
172  public function getOauthVerifier()
173  {
174  if (!isset($this->_oauthVerifier) || isEmpty($this->_oauthVerifier)) {
175  throw new TokenResponseException("oAuth verifier must be obtained during request token request.");
176  }
177  return $this->_oauthVerifier;
178  }
179 
190  $method,
191  UriInterface $uri,
192  TokenInterface $token,
193  $bodyParams = null
194  ) {
195  $this->signature->setTokenSecret($token->getAccessTokenSecret());
196  $parameters = $this->getBasicAuthorizationHeaderInfo();
197  if (isset($parameters['oauth_callback'])) {
198  unset($parameters['oauth_callback']);
199  }
200 
201  $parameters = array_merge($parameters, ['oauth_token' => $token->getAccessToken()]);
202  $parameters = array_merge($parameters, $bodyParams);
203  $parameters['oauth_signature'] = $this->signature->getSignature($uri, $parameters, $method);
204 
205  $authorizationHeader = 'OAuth ';
206  $delimiter = '';
207 
208  foreach ($parameters as $key => $value) {
209  $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
210  $delimiter = ', ';
211  }
212 
213  return $authorizationHeader;
214  }
215 
226  public function buildOauthAuthorizationHeader($uri, $token, $tokenSecret, $bodyParams, $method = 'GET')
227  {
228  $uri = new Uri($uri);
229  $tokenObj = new StdOAuth1Token();
230  $tokenObj->setAccessToken($token);
231  $tokenObj->setAccessTokenSecret($tokenSecret);
232  $tokenObj->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
233  return [
234  'Authorization: ' . $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $tokenObj, $bodyParams)
235  ];
236  }
237 
245  {
246  return [
247  'Authorization: Bearer ' . $token
248  ];
249  }
250 
259  public function validateAccessToken($token, $method = 'GET')
260  {
261  //Need to add Accept header else Magento errors out with 503
262  $extraAuthenticationHeaders = ['Accept' => 'application/json'];
263 
264  $this->signature->setTokenSecret($token->getAccessTokenSecret());
265 
266  $authorizationHeader = [
267  'Authorization' => $this->buildAuthorizationHeaderForAPIRequest(
268  $method,
269  $this->getTestApiEndpoint(),
270  $token,
271  []
272  ),
273  ];
274 
275  $headers = array_merge($authorizationHeader, $extraAuthenticationHeaders);
276 
277  $responseBody = $this->httpClient->retrieveResponse($this->getTestApiEndpoint(), [], $headers, $method);
278 
279  return json_decode($responseBody);
280  }
281 }
buildOauthAuthorizationHeader($uri, $token, $tokenSecret, $bodyParams, $method='GET')
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$value
Definition: gender.phtml:16
$method
Definition: info.phtml:13
__construct(Credentials $credentials, ClientInterface $httpClient=null, TokenStorageInterface $storage=null, SignatureInterface $signature=null, UriInterface $baseApiUri=null)
Definition: OauthClient.php:35
buildAuthorizationHeaderForAPIRequest( $method, UriInterface $uri, TokenInterface $token, $bodyParams=null)