AbstractService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. $token = $this->parseAccessTokenResponse($responseBody);
  195. $this->storage->storeAccessToken($this->service(), $token);
  196. return $token;
  197. }
  198. /**
  199. * Return whether or not the passed scope value is valid.
  200. *
  201. * @param string $scope
  202. *
  203. * @return bool
  204. */
  205. public function isValidScope($scope)
  206. {
  207. $reflectionClass = new \ReflectionClass(get_class($this));
  208. return in_array($scope, $reflectionClass->getConstants(), true);
  209. }
  210. /**
  211. * Check if the given service need to generate a unique state token to build the authorization url
  212. *
  213. * @return bool
  214. */
  215. public function needsStateParameterInAuthUrl()
  216. {
  217. return $this->stateParameterInAuthUrl;
  218. }
  219. /**
  220. * Validates the authorization state against a given one
  221. *
  222. * @param string $state
  223. * @throws InvalidAuthorizationStateException
  224. */
  225. protected function validateAuthorizationState($state)
  226. {
  227. if ($this->retrieveAuthorizationState() !== $state) {
  228. throw new InvalidAuthorizationStateException();
  229. }
  230. }
  231. /**
  232. * Generates a random string to be used as state
  233. *
  234. * @return string
  235. */
  236. protected function generateAuthorizationState()
  237. {
  238. return md5(rand());
  239. }
  240. /**
  241. * Retrieves the authorization state for the current service
  242. *
  243. * @return string
  244. */
  245. protected function retrieveAuthorizationState()
  246. {
  247. return $this->storage->retrieveAuthorizationState($this->service());
  248. }
  249. /**
  250. * Stores a given authorization state into the storage
  251. *
  252. * @param string $state
  253. */
  254. protected function storeAuthorizationState($state)
  255. {
  256. $this->storage->storeAuthorizationState($this->service(), $state);
  257. }
  258. /**
  259. * Return any additional headers always needed for this service implementation's OAuth calls.
  260. *
  261. * @return array
  262. */
  263. protected function getExtraOAuthHeaders()
  264. {
  265. return array();
  266. }
  267. /**
  268. * Return any additional headers always needed for this service implementation's API calls.
  269. *
  270. * @return array
  271. */
  272. protected function getExtraApiHeaders()
  273. {
  274. return array();
  275. }
  276. /**
  277. * Parses the access token response and returns a TokenInterface.
  278. *
  279. * @abstract
  280. *
  281. * @param string $responseBody
  282. *
  283. * @return TokenInterface
  284. *
  285. * @throws TokenResponseException
  286. */
  287. abstract protected function parseAccessTokenResponse($responseBody);
  288. /**
  289. * Returns a class constant from ServiceInterface defining the authorization method used for the API
  290. * Header is the sane default.
  291. *
  292. * @return int
  293. */
  294. protected function getAuthorizationMethod()
  295. {
  296. return static::AUTHORIZATION_METHOD_HEADER_OAUTH;
  297. }
  298. /**
  299. * Returns api version string if is set else retrun empty string
  300. *
  301. * @return string
  302. */
  303. protected function getApiVersionString()
  304. {
  305. return !(empty($this->apiVersion)) ? "/".$this->apiVersion : "" ;
  306. }
  307. /**
  308. * Returns delimiter to scopes in getAuthorizationUri
  309. * For services that do not fully respect the Oauth's RFC,
  310. * and use scopes with commas as delimiter
  311. *
  312. * @return string
  313. */
  314. protected function getScopesDelimiter()
  315. {
  316. return ' ';
  317. }
  318. }