AccessToken.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. namespace OAuth2\ResponseType;
  3. use OAuth2\Storage\AccessTokenInterface as AccessTokenStorageInterface;
  4. use OAuth2\Storage\RefreshTokenInterface;
  5. /**
  6. *
  7. * @author Brent Shaffer <bshafs at gmail dot com>
  8. */
  9. class AccessToken implements AccessTokenInterface
  10. {
  11. protected $tokenStorage;
  12. protected $refreshStorage;
  13. protected $config;
  14. /**
  15. * @param OAuth2\Storage\AccessTokenInterface $tokenStorage REQUIRED Storage class for saving access token information
  16. * @param OAuth2\Storage\RefreshTokenInterface $refreshStorage OPTIONAL Storage class for saving refresh token information
  17. * @param array $config OPTIONAL Configuration options for the server
  18. * <code>
  19. * $config = array(
  20. * 'token_type' => 'bearer', // token type identifier
  21. * 'access_lifetime' => 3600, // time before access token expires
  22. * 'refresh_token_lifetime' => 1209600, // time before refresh token expires
  23. * );
  24. * </endcode>
  25. */
  26. public function __construct(AccessTokenStorageInterface $tokenStorage, RefreshTokenInterface $refreshStorage = null, array $config = array())
  27. {
  28. $this->tokenStorage = $tokenStorage;
  29. $this->refreshStorage = $refreshStorage;
  30. $this->config = array_merge(array(
  31. 'token_type' => 'bearer',
  32. 'access_lifetime' => 3600,
  33. 'refresh_token_lifetime' => 1209600,
  34. ), $config);
  35. }
  36. public function getAuthorizeResponse($params, $user_id = null)
  37. {
  38. // build the URL to redirect to
  39. $result = array('query' => array());
  40. $params += array('scope' => null, 'state' => null);
  41. /*
  42. * a refresh token MUST NOT be included in the fragment
  43. *
  44. * @see http://tools.ietf.org/html/rfc6749#section-4.2.2
  45. */
  46. $includeRefreshToken = false;
  47. $result["fragment"] = $this->createAccessToken($params['client_id'], $user_id, $params['scope'], $includeRefreshToken);
  48. if (isset($params['state'])) {
  49. $result["fragment"]["state"] = $params['state'];
  50. }
  51. return array($params['redirect_uri'], $result);
  52. }
  53. /**
  54. * Handle the creation of access token, also issue refresh token if supported / desirable.
  55. *
  56. * @param $client_id client identifier related to the access token.
  57. * @param $user_id user ID associated with the access token
  58. * @param $scope OPTIONAL scopes to be stored in space-separated string.
  59. * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response
  60. *
  61. * @see http://tools.ietf.org/html/rfc6749#section-5
  62. * @ingroup oauth2_section_5
  63. */
  64. public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
  65. {
  66. $token = array(
  67. "access_token" => $this->generateAccessToken(),
  68. "expires_in" => $this->config['access_lifetime'],
  69. "token_type" => $this->config['token_type'],
  70. "scope" => $scope
  71. );
  72. $this->tokenStorage->setAccessToken($token["access_token"], $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
  73. /*
  74. * Issue a refresh token also, if we support them
  75. *
  76. * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
  77. * is supplied in the constructor
  78. */
  79. if ($includeRefreshToken && $this->refreshStorage) {
  80. $token["refresh_token"] = $this->generateRefreshToken();
  81. $expires = 0;
  82. if ($this->config['refresh_token_lifetime'] > 0) {
  83. $expires = time() + $this->config['refresh_token_lifetime'];
  84. }
  85. $this->refreshStorage->setRefreshToken($token['refresh_token'], $client_id, $user_id, $expires, $scope);
  86. }
  87. return $token;
  88. }
  89. /**
  90. * Generates an unique access token.
  91. *
  92. * Implementing classes may want to override this function to implement
  93. * other access token generation schemes.
  94. *
  95. * @return
  96. * An unique access token.
  97. *
  98. * @ingroup oauth2_section_4
  99. */
  100. protected function generateAccessToken()
  101. {
  102. if (function_exists('openssl_random_pseudo_bytes')) {
  103. $randomData = openssl_random_pseudo_bytes(20);
  104. if ($randomData !== false && strlen($randomData) === 20) {
  105. return bin2hex($randomData);
  106. }
  107. }
  108. if (function_exists('mcrypt_create_iv')) {
  109. $randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
  110. if ($randomData !== false && strlen($randomData) === 20) {
  111. return bin2hex($randomData);
  112. }
  113. }
  114. if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
  115. $randomData = file_get_contents('/dev/urandom', false, null, 0, 20);
  116. if ($randomData !== false && strlen($randomData) === 20) {
  117. return bin2hex($randomData);
  118. }
  119. }
  120. // Last resort which you probably should just get rid of:
  121. $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
  122. return substr(hash('sha512', $randomData), 0, 40);
  123. }
  124. /**
  125. * Generates an unique refresh token
  126. *
  127. * Implementing classes may want to override this function to implement
  128. * other refresh token generation schemes.
  129. *
  130. * @return
  131. * An unique refresh.
  132. *
  133. * @ingroup oauth2_section_4
  134. * @see OAuth2::generateAccessToken()
  135. */
  136. protected function generateRefreshToken()
  137. {
  138. return $this->generateAccessToken(); // let's reuse the same scheme for token generation
  139. }
  140. /**
  141. * Handle the revoking of refresh tokens, and access tokens if supported / desirable
  142. * RFC7009 specifies that "If the server is unable to locate the token using
  143. * the given hint, it MUST extend its search across all of its supported token types"
  144. *
  145. * @param $token
  146. * @param null $tokenTypeHint
  147. * @return boolean
  148. */
  149. public function revokeToken($token, $tokenTypeHint = null)
  150. {
  151. if ($tokenTypeHint == 'refresh_token') {
  152. if ($this->refreshStorage && $revoked = $this->refreshStorage->unsetRefreshToken($token)) {
  153. return true;
  154. }
  155. }
  156. /** @TODO remove in v2 */
  157. if (!method_exists($this->tokenStorage, 'unsetAccessToken')) {
  158. throw new \RuntimeException(
  159. sprintf('Token storage %s must implement unsetAccessToken method', get_class($this->tokenStorage)
  160. ));
  161. }
  162. $revoked = $this->tokenStorage->unsetAccessToken($token);
  163. // if a typehint is supplied and fails, try other storages
  164. // @see https://tools.ietf.org/html/rfc7009#section-2.1
  165. if (!$revoked && $tokenTypeHint != 'refresh_token') {
  166. if ($this->refreshStorage) {
  167. $revoked = $this->refreshStorage->unsetRefreshToken($token);
  168. }
  169. }
  170. return $revoked;
  171. }
  172. }