AbstractService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. namespace OAuth\OAuth2\Service;
  3. use OAuth\Common\Consumer\CredentialsInterface;
  4. use OAuth\Common\Exception\Exception;
  5. use OAuth\Common\Service\AbstractService as BaseAbstractService;
  6. use OAuth\Common\Storage\TokenStorageInterface;
  7. use OAuth\Common\Http\Exception\TokenResponseException;
  8. use OAuth\Common\Http\Client\ClientInterface;
  9. use OAuth\Common\Http\Uri\UriInterface;
  10. use OAuth\OAuth2\Service\Exception\InvalidAuthorizationStateException;
  11. use OAuth\OAuth2\Service\Exception\InvalidScopeException;
  12. use OAuth\OAuth2\Service\Exception\MissingRefreshTokenException;
  13. use OAuth\Common\Token\TokenInterface;
  14. use OAuth\Common\Token\Exception\ExpiredTokenException;
  15. abstract class AbstractService extends BaseAbstractService implements ServiceInterface
  16. {
  17. /** @const OAUTH_VERSION */
  18. const OAUTH_VERSION = 2;
  19. /** @var array */
  20. protected $scopes;
  21. /** @var UriInterface|null */
  22. protected $baseApiUri;
  23. /** @var bool */
  24. protected $stateParameterInAuthUrl;
  25. /** @var string */
  26. protected $apiVersion;
  27. /**
  28. * @param CredentialsInterface $credentials
  29. * @param ClientInterface $httpClient
  30. * @param TokenStorageInterface $storage
  31. * @param array $scopes
  32. * @param UriInterface|null $baseApiUri
  33. * @param bool $stateParameterInAutUrl
  34. * @param string $apiVersion
  35. *
  36. * @throws InvalidScopeException
  37. */
  38. public function __construct(
  39. CredentialsInterface $credentials,
  40. ClientInterface $httpClient,
  41. TokenStorageInterface $storage,
  42. $scopes = array(),
  43. UriInterface $baseApiUri = null,
  44. $stateParameterInAutUrl = false,
  45. $apiVersion = ""
  46. ) {
  47. parent::__construct($credentials, $httpClient, $storage);
  48. $this->stateParameterInAuthUrl = $stateParameterInAutUrl;
  49. foreach ($scopes as $scope) {
  50. if (!$this->isValidScope($scope)) {
  51. throw new InvalidScopeException('Scope ' . $scope . ' is not valid for service ' . get_class($this));
  52. }
  53. }
  54. $this->scopes = $scopes;
  55. $this->baseApiUri = $baseApiUri;
  56. $this->apiVersion = $apiVersion;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getAuthorizationUri(array $additionalParameters = array())
  62. {
  63. $parameters = array_merge(
  64. $additionalParameters,
  65. array(
  66. 'type' => 'web_server',
  67. 'client_id' => $this->credentials->getConsumerId(),
  68. 'redirect_uri' => $this->credentials->getCallbackUrl(),
  69. 'response_type' => 'code',
  70. )
  71. );
  72. $parameters['scope'] = implode($this->getScopesDelimiter(), $this->scopes);
  73. if ($this->needsStateParameterInAuthUrl()) {
  74. if (!isset($parameters['state'])) {
  75. $parameters['state'] = $this->generateAuthorizationState();
  76. }
  77. $this->storeAuthorizationState($parameters['state']);
  78. }
  79. // Build the url
  80. $url = clone $this->getAuthorizationEndpoint();
  81. foreach ($parameters as $key => $val) {
  82. $url->addToQuery($key, $val);
  83. }
  84. return $url;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function requestAccessToken($code, $state = null)
  90. {
  91. if (null !== $state) {
  92. $this->validateAuthorizationState($state);
  93. }
  94. $bodyParams = array(
  95. 'code' => $code,
  96. 'client_id' => $this->credentials->getConsumerId(),
  97. 'client_secret' => $this->credentials->getConsumerSecret(),
  98. 'redirect_uri' => $this->credentials->getCallbackUrl(),
  99. 'grant_type' => 'authorization_code',
  100. );
  101. $responseBody = $this->httpClient->retrieveResponse(
  102. $this->getAccessTokenEndpoint(),
  103. $bodyParams,
  104. $this->getExtraOAuthHeaders()
  105. );
  106. $token = $this->parseAccessTokenResponse($responseBody);
  107. $this->storage->storeAccessToken($this->service(), $token);
  108. return $token;
  109. }
  110. /**
  111. * Sends an authenticated API request to the path provided.
  112. * If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used.
  113. *
  114. * @param string|UriInterface $path
  115. * @param string $method HTTP method
  116. * @param array $body Request body if applicable.
  117. * @param array $extraHeaders Extra headers if applicable. These will override service-specific
  118. * any defaults.
  119. *
  120. * @return string
  121. *
  122. * @throws ExpiredTokenException
  123. * @throws Exception
  124. */
  125. public function request($path, $method = 'GET', $body = null, array $extraHeaders = array())
  126. {
  127. $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri);
  128. $token = $this->storage->retrieveAccessToken($this->service());
  129. if ($token->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES
  130. && $token->getEndOfLife() !== TokenInterface::EOL_UNKNOWN
  131. && time() > $token->getEndOfLife()
  132. ) {
  133. throw new ExpiredTokenException(
  134. sprintf(
  135. 'Token expired on %s at %s',
  136. date('m/d/Y', $token->getEndOfLife()),
  137. date('h:i:s A', $token->getEndOfLife())
  138. )
  139. );
  140. }
  141. // add the token where it may be needed
  142. if (static::AUTHORIZATION_METHOD_HEADER_OAUTH === $this->getAuthorizationMethod()) {
  143. $extraHeaders = array_merge(array('Authorization' => 'OAuth ' . $token->getAccessToken()), $extraHeaders);
  144. } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING === $this->getAuthorizationMethod()) {
  145. $uri->addToQuery('access_token', $token->getAccessToken());
  146. } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V2 === $this->getAuthorizationMethod()) {
  147. $uri->addToQuery('oauth2_access_token', $token->getAccessToken());
  148. } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V3 === $this->getAuthorizationMethod()) {
  149. $uri->addToQuery('apikey', $token->getAccessToken());
  150. } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V4 === $this->getAuthorizationMethod()) {
  151. $uri->addToQuery('auth', $token->getAccessToken());
  152. } elseif (static::AUTHORIZATION_METHOD_HEADER_BEARER === $this->getAuthorizationMethod()) {
  153. $extraHeaders = array_merge(array('Authorization' => 'Bearer ' . $token->getAccessToken()), $extraHeaders);
  154. }
  155. $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders);
  156. return $this->httpClient->retrieveResponse($uri, $body, $extraHeaders, $method);
  157. }
  158. /**
  159. * Accessor to the storage adapter to be able to retrieve tokens
  160. *
  161. * @return TokenStorageInterface
  162. */
  163. public function getStorage()
  164. {
  165. return $this->storage;
  166. }
  167. /**
  168. * Refreshes an OAuth2 access token.
  169. *
  170. * @param TokenInterface $token
  171. *
  172. * @return TokenInterface $token
  173. *
  174. * @throws MissingRefreshTokenException
  175. */
  176. public function refreshAccessToken(TokenInterface $token)
  177. {
  178. $refreshToken = $token->getRefreshToken();
  179. if (empty($refreshToken)) {
  180. throw new MissingRefreshTokenException();
  181. }
  182. $parameters = array(
  183. 'grant_type' => 'refresh_token',
  184. 'type' => 'web_server',
  185. 'client_id' => $this->credentials->getConsumerId(),
  186. 'client_secret' => $this->credentials->getConsumerSecret(),
  187. 'refresh_token' => $refreshToken,
  188. );
  189. $responseBody = $this->httpClient->retrieveResponse(
  190. $this->getAccessTokenEndpoint(),
  191. $parameters,
  192. $this->getExtraOAuthHeaders()
  193. );
  194. //print $responseBody;exit; // We must have a result "{"token_type":"Bearer","scope...
  195. $token = $this->parseAccessTokenResponse($responseBody);
  196. $this->storage->storeAccessToken($this->service(), $token);
  197. return $token;
  198. }
  199. /**
  200. * Return whether or not the passed scope value is valid.
  201. *
  202. * @param string $scope
  203. *
  204. * @return bool
  205. */
  206. public function isValidScope($scope)
  207. {
  208. $reflectionClass = new \ReflectionClass(get_class($this));
  209. return in_array($scope, $reflectionClass->getConstants(), true);
  210. }
  211. /**
  212. * Check if the given service need to generate a unique state token to build the authorization url
  213. *
  214. * @return bool
  215. */
  216. public function needsStateParameterInAuthUrl()
  217. {
  218. return $this->stateParameterInAuthUrl;
  219. }
  220. /**
  221. * Validates the authorization state against a given one
  222. *
  223. * @param string $state
  224. * @throws InvalidAuthorizationStateException
  225. */
  226. protected function validateAuthorizationState($state)
  227. {
  228. if ($this->retrieveAuthorizationState() !== $state) {
  229. throw new InvalidAuthorizationStateException();
  230. }
  231. }
  232. /**
  233. * Generates a random string to be used as state
  234. *
  235. * @return string
  236. */
  237. protected function generateAuthorizationState()
  238. {
  239. return md5(rand());
  240. }
  241. /**
  242. * Retrieves the authorization state for the current service
  243. *
  244. * @return string
  245. */
  246. protected function retrieveAuthorizationState()
  247. {
  248. return $this->storage->retrieveAuthorizationState($this->service());
  249. }
  250. /**
  251. * Stores a given authorization state into the storage
  252. *
  253. * @param string $state
  254. */
  255. protected function storeAuthorizationState($state)
  256. {
  257. $this->storage->storeAuthorizationState($this->service(), $state);
  258. }
  259. /**
  260. * Return any additional headers always needed for this service implementation's OAuth calls.
  261. *
  262. * @return array
  263. */
  264. protected function getExtraOAuthHeaders()
  265. {
  266. return array();
  267. }
  268. /**
  269. * Return any additional headers always needed for this service implementation's API calls.
  270. *
  271. * @return array
  272. */
  273. protected function getExtraApiHeaders()
  274. {
  275. return array();
  276. }
  277. /**
  278. * Parses the access token response and returns a TokenInterface.
  279. *
  280. * @abstract
  281. *
  282. * @param string $responseBody
  283. *
  284. * @return TokenInterface
  285. *
  286. * @throws TokenResponseException
  287. */
  288. abstract protected function parseAccessTokenResponse($responseBody);
  289. /**
  290. * Returns a class constant from ServiceInterface defining the authorization method used for the API
  291. * Header is the sane default.
  292. *
  293. * @return int
  294. */
  295. protected function getAuthorizationMethod()
  296. {
  297. return static::AUTHORIZATION_METHOD_HEADER_OAUTH;
  298. }
  299. /**
  300. * Returns api version string if is set else retrun empty string
  301. *
  302. * @return string
  303. */
  304. protected function getApiVersionString()
  305. {
  306. return !(empty($this->apiVersion)) ? "/".$this->apiVersion : "" ;
  307. }
  308. /**
  309. * Returns delimiter to scopes in getAuthorizationUri
  310. * For services that do not fully respect the Oauth's RFC,
  311. * and use scopes with commas as delimiter
  312. *
  313. * @return string
  314. */
  315. protected function getScopesDelimiter()
  316. {
  317. return ' ';
  318. }
  319. }