PageRenderTime 118ms CodeModel.GetById 31ms RepoModel.GetById 4ms app.codeStats 0ms

/lib/OAuth2.php

https://github.com/thomascoding/oauth2-php
PHP | 1138 lines | 420 code | 139 blank | 579 comment | 91 complexity | 107d7fdc372a3f7d67860141f6fd40c3 MD5 | raw file
Possible License(s): MIT
  1. <?php
  2. require 'OAuth2ServerException.php';
  3. require 'OAuth2AuthenticateException.php';
  4. require 'OAuth2RedirectException.php';
  5. /**
  6. * @mainpage
  7. * OAuth 2.0 server in PHP, originally written for
  8. * <a href="http://www.opendining.net/"> Open Dining</a>. Supports
  9. * <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-20">IETF draft v20</a>.
  10. *
  11. * Source repo has sample servers implementations for
  12. * <a href="http://php.net/manual/en/book.pdo.php"> PHP Data Objects</a> and
  13. * <a href="http://www.mongodb.org/">MongoDB</a>. Easily adaptable to other
  14. * storage engines.
  15. *
  16. * PHP Data Objects supports a variety of databases, including MySQL,
  17. * Microsoft SQL Server, SQLite, and Oracle, so you can try out the sample
  18. * to see how it all works.
  19. *
  20. * We're expanding the wiki to include more helpful documentation, but for
  21. * now, your best bet is to view the oauth.php source - it has lots of
  22. * comments.
  23. *
  24. * @author Tim Ridgely <tim.ridgely@gmail.com>
  25. * @author Aaron Parecki <aaron@parecki.com>
  26. * @author Edison Wong <hswong3i@pantarei-design.com>
  27. * @author David Rochwerger <catch.dave@gmail.com>
  28. *
  29. * @see http://code.google.com/p/oauth2-php/
  30. * @see https://github.com/quizlet/oauth2-php
  31. */
  32. /**
  33. * OAuth2.0 draft v20 server-side implementation.
  34. *
  35. * @todo Add support for Message Authentication Code (MAC) token type.
  36. *
  37. * @author Originally written by Tim Ridgely <tim.ridgely@gmail.com>.
  38. * @author Updated to draft v10 by Aaron Parecki <aaron@parecki.com>.
  39. * @author Debug, coding style clean up and documented by Edison Wong <hswong3i@pantarei-design.com>.
  40. * @author Refactored (including separating from raw POST/GET) and updated to draft v20 by David Rochwerger <catch.dave@gmail.com>.
  41. */
  42. class OAuth2 {
  43. /**
  44. * Array of persistent variables stored.
  45. */
  46. protected $conf = array();
  47. /**
  48. * Storage engine for authentication server
  49. *
  50. * @var IOAuth2Storage
  51. */
  52. protected $storage;
  53. /**
  54. * Keep track of the old refresh token. So we can unset
  55. * the old refresh tokens when a new one is issued.
  56. *
  57. * @var string
  58. */
  59. protected $oldRefreshToken;
  60. /**
  61. * Default values for configuration options.
  62. *
  63. * @var int
  64. * @see OAuth2::setDefaultOptions()
  65. */
  66. const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
  67. const DEFAULT_REFRESH_TOKEN_LIFETIME = 1209600;
  68. const DEFAULT_AUTH_CODE_LIFETIME = 30;
  69. const DEFAULT_WWW_REALM = 'Service';
  70. /**
  71. * Configurable options.
  72. *
  73. * @var string
  74. */
  75. const CONFIG_ACCESS_LIFETIME = 'access_token_lifetime'; // The lifetime of access token in seconds.
  76. const CONFIG_REFRESH_LIFETIME = 'refresh_token_lifetime'; // The lifetime of refresh token in seconds.
  77. const CONFIG_AUTH_LIFETIME = 'auth_code_lifetime'; // The lifetime of auth code in seconds.
  78. const CONFIG_SUPPORTED_SCOPES = 'supported_scopes'; // Array of scopes you want to support
  79. const CONFIG_TOKEN_TYPE = 'token_type'; // Token type to respond with. Currently only "Bearer" supported.
  80. const CONFIG_WWW_REALM = 'realm';
  81. const CONFIG_ENFORCE_INPUT_REDIRECT = 'enforce_redirect'; // Set to true to enforce redirect_uri on input for both authorize and token steps.
  82. const CONFIG_ENFORCE_STATE = 'enforce_state'; // Set to true to enforce state to be passed in authorization (see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12)
  83. /**
  84. * Regex to filter out the client identifier (described in Section 2 of IETF draft).
  85. *
  86. * IETF draft does not prescribe a format for these, however I've arbitrarily
  87. * chosen alphanumeric strings with hyphens and underscores, 3-32 characters
  88. * long.
  89. *
  90. * Feel free to change.
  91. */
  92. const CLIENT_ID_REGEXP = '/^[a-z0-9-_]{3,32}$/i';
  93. /**
  94. * @defgroup oauth2_section_5 Accessing a Protected Resource
  95. * @{
  96. *
  97. * Clients access protected resources by presenting an access token to
  98. * the resource server. Access tokens act as bearer tokens, where the
  99. * token string acts as a shared symmetric secret. This requires
  100. * treating the access token with the same care as other secrets (e.g.
  101. * end-user passwords). Access tokens SHOULD NOT be sent in the clear
  102. * over an insecure channel.
  103. *
  104. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
  105. */
  106. /**
  107. * Used to define the name of the OAuth access token parameter
  108. * (POST & GET). This is for the "bearer" token type.
  109. * Other token types may use different methods and names.
  110. *
  111. * IETF Draft section 2 specifies that it should be called "access_token"
  112. *
  113. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.2
  114. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.3
  115. */
  116. const TOKEN_PARAM_NAME = 'access_token';
  117. /**
  118. * When using the bearer token type, there is a specifc Authorization header
  119. * required: "Bearer"
  120. *
  121. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-04#section-2.1
  122. */
  123. const TOKEN_BEARER_HEADER_NAME = 'Bearer';
  124. /**
  125. * @}
  126. */
  127. /**
  128. * @defgroup oauth2_section_4 Obtaining Authorization
  129. * @{
  130. *
  131. * When the client interacts with an end-user, the end-user MUST first
  132. * grant the client authorization to access its protected resources.
  133. * Once obtained, the end-user authorization grant is expressed as an
  134. * authorization code which the client uses to obtain an access token.
  135. * To obtain an end-user authorization, the client sends the end-user to
  136. * the end-user authorization endpoint.
  137. *
  138. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
  139. */
  140. /**
  141. * List of possible authentication response types.
  142. * The "authorization_code" mechanism exclusively supports 'code'
  143. * and the "implicit" mechanism exclusively supports 'token'.
  144. *
  145. * @var string
  146. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
  147. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.1
  148. */
  149. const RESPONSE_TYPE_AUTH_CODE = 'code';
  150. const RESPONSE_TYPE_ACCESS_TOKEN = 'token';
  151. /**
  152. * @}
  153. */
  154. /**
  155. * @defgroup oauth2_section_5 Obtaining an Access Token
  156. * @{
  157. *
  158. * The client obtains an access token by authenticating with the
  159. * authorization server and presenting its authorization grant (in the form of
  160. * an authorization code, resource owner credentials, an assertion, or a
  161. * refresh token).
  162. *
  163. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
  164. */
  165. /**
  166. * Grant types support by draft 20
  167. */
  168. const GRANT_TYPE_AUTH_CODE = 'authorization_code';
  169. const GRANT_TYPE_IMPLICIT = 'token';
  170. const GRANT_TYPE_USER_CREDENTIALS = 'password';
  171. const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
  172. const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
  173. const GRANT_TYPE_EXTENSIONS = 'extensions';
  174. /**
  175. * Regex to filter out the grant type.
  176. * NB: For extensibility, the grant type can be a URI
  177. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.5
  178. */
  179. const GRANT_TYPE_REGEXP = '#^(authorization_code|token|password|client_credentials|refresh_token|http://.*)$#';
  180. /**
  181. * @}
  182. */
  183. /**
  184. * Possible token types as defined by draft 20.
  185. *
  186. * TODO: Add support for mac (and maybe other types?)
  187. *
  188. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7.1
  189. */
  190. const TOKEN_TYPE_BEARER = 'bearer';
  191. const TOKEN_TYPE_MAC = 'mac'; // Currently unsupported
  192. /**
  193. * @defgroup self::HTTP_status HTTP status code
  194. * @{
  195. */
  196. /**
  197. * HTTP status codes for successful and error states as specified by draft 20.
  198. *
  199. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2
  200. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  201. */
  202. const HTTP_FOUND = '302 Found';
  203. const HTTP_BAD_REQUEST = '400 Bad Request';
  204. const HTTP_UNAUTHORIZED = '401 Unauthorized';
  205. const HTTP_FORBIDDEN = '403 Forbidden';
  206. const HTTP_UNAVAILABLE = '503 Service Unavailable';
  207. /**
  208. * @}
  209. */
  210. /**
  211. * @defgroup oauth2_error Error handling
  212. * @{
  213. *
  214. * @todo Extend for i18n.
  215. * @todo Consider moving all error related functionality into a separate class.
  216. */
  217. /**
  218. * The request is missing a required parameter, includes an unsupported
  219. * parameter or parameter value, or is otherwise malformed.
  220. *
  221. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  222. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  223. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  224. */
  225. const ERROR_INVALID_REQUEST = 'invalid_request';
  226. /**
  227. * The client identifier provided is invalid.
  228. *
  229. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  230. */
  231. const ERROR_INVALID_CLIENT = 'invalid_client';
  232. /**
  233. * The client is not authorized to use the requested response type.
  234. *
  235. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  236. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  237. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  238. */
  239. const ERROR_UNAUTHORIZED_CLIENT = 'unauthorized_client';
  240. /**
  241. * The redirection URI provided does not match a pre-registered value.
  242. *
  243. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2.4
  244. */
  245. const ERROR_REDIRECT_URI_MISMATCH = 'redirect_uri_mismatch';
  246. /**
  247. * The end-user or authorization server denied the request.
  248. * This could be returned, for example, if the resource owner decides to reject
  249. * access to the client at a later point.
  250. *
  251. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  252. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  253. */
  254. const ERROR_USER_DENIED = 'access_denied';
  255. /**
  256. * The requested response type is not supported by the authorization server.
  257. *
  258. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  259. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  260. */
  261. const ERROR_UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type';
  262. /**
  263. * The requested scope is invalid, unknown, or malformed.
  264. *
  265. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  266. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  267. */
  268. const ERROR_INVALID_SCOPE = 'invalid_scope';
  269. /**
  270. * The provided authorization grant is invalid, expired,
  271. * revoked, does not match the redirection URI used in the
  272. * authorization request, or was issued to another client.
  273. *
  274. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  275. */
  276. const ERROR_INVALID_GRANT = 'invalid_grant';
  277. /**
  278. * The authorization grant is not supported by the authorization server.
  279. *
  280. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  281. */
  282. const ERROR_UNSUPPORTED_GRANT_TYPE = 'unsupported_grant_type';
  283. /**
  284. * The request requires higher privileges than provided by the access token.
  285. * The resource server SHOULD respond with the HTTP 403 (Forbidden) status
  286. * code and MAY include the "scope" attribute with the scope necessary to
  287. * access the protected resource.
  288. *
  289. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  290. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  291. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  292. */
  293. const ERROR_INSUFFICIENT_SCOPE = 'invalid_scope';
  294. /**
  295. * @}
  296. */
  297. /**
  298. * Creates an OAuth2.0 server-side instance.
  299. *
  300. * @param $config - An associative array as below of config options. See CONFIG_* constants.
  301. */
  302. public function __construct(IOAuth2Storage $storage, $config = array()) {
  303. $this->storage = $storage;
  304. // Configuration options
  305. $this->setDefaultOptions();
  306. foreach ( $config as $name => $value ) {
  307. $this->setVariable($name, $value);
  308. }
  309. }
  310. /**
  311. * Default configuration options are specified here.
  312. */
  313. protected function setDefaultOptions() {
  314. $this->conf = array(
  315. self::CONFIG_ACCESS_LIFETIME => self::DEFAULT_ACCESS_TOKEN_LIFETIME,
  316. self::CONFIG_REFRESH_LIFETIME => self::DEFAULT_REFRESH_TOKEN_LIFETIME,
  317. self::CONFIG_AUTH_LIFETIME => self::DEFAULT_AUTH_CODE_LIFETIME,
  318. self::CONFIG_WWW_REALM => self::DEFAULT_WWW_REALM,
  319. self::CONFIG_TOKEN_TYPE => self::TOKEN_TYPE_BEARER,
  320. self::CONFIG_ENFORCE_INPUT_REDIRECT => FALSE,
  321. self::CONFIG_ENFORCE_STATE => FALSE,
  322. self::CONFIG_SUPPORTED_SCOPES => array() // This is expected to be passed in on construction. Scopes can be an aribitrary string.
  323. );
  324. }
  325. /**
  326. * Returns a persistent variable.
  327. *
  328. * @param $name
  329. * The name of the variable to return.
  330. * @param $default
  331. * The default value to use if this variable has never been set.
  332. *
  333. * @return
  334. * The value of the variable.
  335. */
  336. public function getVariable($name, $default = NULL) {
  337. $name = strtolower($name);
  338. return isset($this->conf[$name]) ? $this->conf[$name] : $default;
  339. }
  340. /**
  341. * Sets a persistent variable.
  342. *
  343. * @param $name
  344. * The name of the variable to set.
  345. * @param $value
  346. * The value to set.
  347. */
  348. public function setVariable($name, $value) {
  349. $name = strtolower($name);
  350. $this->conf[$name] = $value;
  351. return $this;
  352. }
  353. // Resource protecting (Section 5).
  354. /**
  355. * Check that a valid access token has been provided.
  356. * The token is returned (as an associative array) if valid.
  357. *
  358. * The scope parameter defines any required scope that the token must have.
  359. * If a scope param is provided and the token does not have the required
  360. * scope, we bounce the request.
  361. *
  362. * Some implementations may choose to return a subset of the protected
  363. * resource (i.e. "public" data) if the user has not provided an access
  364. * token or if the access token is invalid or expired.
  365. *
  366. * The IETF spec says that we should send a 401 Unauthorized header and
  367. * bail immediately so that's what the defaults are set to. You can catch
  368. * the exception thrown and behave differently if you like (log errors, allow
  369. * public access for missing tokens, etc)
  370. *
  371. * @param $scope
  372. * A space-separated string of required scope(s), if you want to check
  373. * for scope.
  374. * @return array
  375. * Token
  376. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
  377. *
  378. * @ingroup oauth2_section_7
  379. */
  380. public function verifyAccessToken($token_param, $scope = NULL) {
  381. $tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
  382. $realm = $this->getVariable(self::CONFIG_WWW_REALM);
  383. if (!$token_param) { // Access token was not provided
  384. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.', $scope);
  385. }
  386. // Get the stored token data (from the implementing subclass)
  387. $token = $this->storage->getAccessToken($token_param);
  388. if ($token === NULL) {
  389. throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided is invalid.', $scope);
  390. }
  391. // Check we have a well formed token
  392. if (!isset($token["expires"]) || !isset($token["client_id"])) {
  393. throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'Malformed token (missing "expires" or "client_id")', $scope);
  394. }
  395. // Check token expiration (expires is a mandatory paramter)
  396. if (isset($token["expires"]) && time() > $token["expires"]) {
  397. throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided has expired.', $scope);
  398. }
  399. // Check scope, if provided
  400. // If token doesn't have a scope, it's NULL/empty, or it's insufficient, then throw an error
  401. if ($scope && (!isset($token["scope"]) || !$token["scope"] || !$this->checkScope($scope, $token["scope"]))) {
  402. throw new OAuth2AuthenticateException(self::HTTP_FORBIDDEN, $tokenType, $realm, self::ERROR_INSUFFICIENT_SCOPE, 'The request requires higher privileges than provided by the access token.', $scope);
  403. }
  404. return $token;
  405. }
  406. /**
  407. * This is a convenience function that can be used to get the token, which can then
  408. * be passed to verifyAccessToken(). The constraints specified by the draft are
  409. * attempted to be adheared to in this method.
  410. *
  411. * As per the Bearer spec (draft 8, section 2) - there are three ways for a client
  412. * to specify the bearer token, in order of preference: Authorization Header,
  413. * POST and GET.
  414. *
  415. * NB: Resource servers MUST accept tokens via the Authorization scheme
  416. * (http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2).
  417. *
  418. * @todo Should we enforce TLS/SSL in this function?
  419. *
  420. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.1
  421. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.2
  422. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.3
  423. *
  424. * Old Android version bug (at least with version 2.2)
  425. * @see http://code.google.com/p/android/issues/detail?id=6684
  426. *
  427. * We don't want to test this functionality as it relies on superglobals and headers:
  428. * @codeCoverageIgnoreStart
  429. */
  430. public function getBearerToken() {
  431. if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
  432. $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
  433. } elseif (function_exists('apache_request_headers')) {
  434. $requestHeaders = apache_request_headers();
  435. // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
  436. $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
  437. if (isset($requestHeaders['Authorization'])) {
  438. $headers = trim($requestHeaders['Authorization']);
  439. }
  440. }
  441. $tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
  442. $realm = $this->getVariable(self::CONFIG_WWW_REALM);
  443. // Check that exactly one method was used
  444. $methodsUsed = !empty($headers) + isset($_GET[self::TOKEN_PARAM_NAME]) + isset($_POST[self::TOKEN_PARAM_NAME]);
  445. if ($methodsUsed > 1) {
  446. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Only one method may be used to authenticate at a time (Auth header, GET or POST).');
  447. } elseif ($methodsUsed == 0) {
  448. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The access token was not found.');
  449. }
  450. // HEADER: Get the access token from the header
  451. if (!empty($headers)) {
  452. if (!preg_match('/' . self::TOKEN_BEARER_HEADER_NAME . '\s(\S+)/', $headers, $matches)) {
  453. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Malformed auth header');
  454. }
  455. return $matches[1];
  456. }
  457. // POST: Get the token from POST data
  458. if (isset($_POST[self::TOKEN_PARAM_NAME])) {
  459. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  460. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'When putting the token in the body, the method must be POST.');
  461. }
  462. // IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
  463. if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] != 'application/x-www-form-urlencoded') {
  464. throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The content type for POST requests must be "application/x-www-form-urlencoded"');
  465. }
  466. return $_POST[self::TOKEN_PARAM_NAME];
  467. }
  468. // GET method
  469. return $_GET[self::TOKEN_PARAM_NAME];
  470. }
  471. /** @codeCoverageIgnoreEnd */
  472. /**
  473. * Check if everything in required scope is contained in available scope.
  474. *
  475. * @param $required_scope
  476. * Required scope to be check with.
  477. *
  478. * @return
  479. * TRUE if everything in required scope is contained in available scope,
  480. * and False if it isn't.
  481. *
  482. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
  483. *
  484. * @ingroup oauth2_section_7
  485. */
  486. private function checkScope($required_scope, $available_scope) {
  487. // The required scope should match or be a subset of the available scope
  488. if (!is_array($required_scope)) {
  489. $required_scope = explode(' ', trim($required_scope));
  490. }
  491. if (!is_array($available_scope)) {
  492. $available_scope = explode(' ', trim($available_scope));
  493. }
  494. return (count(array_diff($required_scope, $available_scope)) == 0);
  495. }
  496. // Access token granting (Section 4).
  497. /**
  498. * Grant or deny a requested access token.
  499. * This would be called from the "/token" endpoint as defined in the spec.
  500. * Obviously, you can call your endpoint whatever you want.
  501. *
  502. * @param $inputData - The draft specifies that the parameters should be
  503. * retrieved from POST, but you can override to whatever method you like.
  504. * @throws OAuth2ServerException
  505. *
  506. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
  507. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.6
  508. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-4.1.3
  509. *
  510. * @ingroup oauth2_section_4
  511. */
  512. public function grantAccessToken(array $inputData = NULL, array $authHeaders = NULL) {
  513. $filters = array(
  514. "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
  515. "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
  516. "code" => array("flags" => FILTER_REQUIRE_SCALAR),
  517. "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
  518. "username" => array("flags" => FILTER_REQUIRE_SCALAR),
  519. "password" => array("flags" => FILTER_REQUIRE_SCALAR),
  520. "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
  521. );
  522. // Input data by default can be either POST or GET
  523. if (!isset($inputData)) {
  524. $inputData = ($_SERVER['REQUEST_METHOD'] == 'POST') ? $_POST : $_GET;
  525. }
  526. // Basic authorization header
  527. $authHeaders = isset($authHeaders) ? $authHeaders : $this->getAuthorizationHeader();
  528. // Filter input data
  529. $input = filter_var_array($inputData, $filters);
  530. // Grant Type must be specified.
  531. if (!$input["grant_type"]) {
  532. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
  533. }
  534. // Authorize the client
  535. $client = $this->getClientCredentials($inputData, $authHeaders);
  536. if ($this->storage->checkClientCredentials($client[0], $client[1]) === FALSE) {
  537. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client credentials are invalid');
  538. }
  539. if (!$this->storage->checkRestrictedGrantType($client[0], $input["grant_type"])) {
  540. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNAUTHORIZED_CLIENT, 'The grant type is unauthorized for this client_id');
  541. }
  542. // Do the granting
  543. switch ($input["grant_type"]) {
  544. case self::GRANT_TYPE_AUTH_CODE:
  545. if (!($this->storage instanceof IOAuth2GrantCode)) {
  546. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  547. }
  548. if (!$input["code"]) {
  549. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameter. "code" is required');
  550. }
  551. if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
  552. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, "The redirect URI parameter is required.");
  553. }
  554. $stored = $this->storage->getAuthCode($input["code"]);
  555. // Check the code exists
  556. if ($stored === NULL || $client[0] != $stored["client_id"]) {
  557. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "Refresh token doesn't exist or is invalid for the client");
  558. }
  559. // Validate the redirect URI. If a redirect URI has been provided on input, it must be validated
  560. if ($input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
  561. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, "The redirect URI is missing or do not match");
  562. }
  563. if ($stored["expires"] < time()) {
  564. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "The authorization code has expired");
  565. }
  566. break;
  567. case self::GRANT_TYPE_USER_CREDENTIALS:
  568. if (!($this->storage instanceof IOAuth2GrantUser)) {
  569. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  570. }
  571. if (!$input["username"] || !$input["password"]) {
  572. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
  573. }
  574. $stored = $this->storage->checkUserCredentials($client[0], $input["username"], $input["password"]);
  575. if ($stored === FALSE) {
  576. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
  577. }
  578. break;
  579. case self::GRANT_TYPE_CLIENT_CREDENTIALS:
  580. if (!($this->storage instanceof IOAuth2GrantClient)) {
  581. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  582. }
  583. if (empty($client[1])) {
  584. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client_secret is mandatory for the "client_credentials" grant type');
  585. }
  586. // NB: We don't need to check for $stored==false, because it was checked above already
  587. $stored = $this->storage->checkClientCredentialsGrant($client[0], $client[1]);
  588. break;
  589. case self::GRANT_TYPE_REFRESH_TOKEN:
  590. if (!($this->storage instanceof IOAuth2RefreshTokens)) {
  591. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  592. }
  593. if (!$input["refresh_token"]) {
  594. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
  595. }
  596. $stored = $this->storage->getRefreshToken($input["refresh_token"]);
  597. if ($stored === NULL || $client[0] != $stored["client_id"]) {
  598. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Invalid refresh token');
  599. }
  600. if ($stored["expires"] < time()) {
  601. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Refresh token has expired');
  602. }
  603. // store the refresh token locally so we can delete it when a new refresh token is generated
  604. $this->oldRefreshToken = $stored["refresh_token"];
  605. break;
  606. case self::GRANT_TYPE_IMPLICIT:
  607. /* TODO: NOT YET IMPLEMENTED */
  608. throw new OAuth2ServerException('501 Not Implemented', 'This OAuth2 library is not yet complete. This functionality is not implemented yet.');
  609. if (!($this->storage instanceof IOAuth2GrantImplicit)) {
  610. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  611. }
  612. break;
  613. // Extended grant types:
  614. case filter_var($input["grant_type"], FILTER_VALIDATE_URL):
  615. if (!($this->storage instanceof IOAuth2GrantExtension)) {
  616. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
  617. }
  618. $uri = filter_var($input["grant_type"], FILTER_VALIDATE_URL);
  619. $stored = $this->storage->checkGrantExtension($uri, $inputData, $authHeaders);
  620. if ($stored === FALSE) {
  621. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
  622. }
  623. break;
  624. default :
  625. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
  626. }
  627. if (!isset($stored["scope"])) {
  628. $stored["scope"] = NULL;
  629. }
  630. // Check scope, if provided
  631. if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
  632. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
  633. }
  634. $user_id = isset($stored['user_id']) ? $stored['user_id'] : null;
  635. $token = $this->createAccessToken($client[0], $user_id, $stored['scope']);
  636. // Send response
  637. $this->sendJsonHeaders();
  638. echo json_encode($token);
  639. }
  640. /**
  641. * Internal function used to get the client credentials from HTTP basic
  642. * auth or POST data.
  643. *
  644. * According to the spec (draft 20), the client_id can be provided in
  645. * the Basic Authorization header (recommended) or via GET/POST.
  646. *
  647. * @return
  648. * A list containing the client identifier and password, for example
  649. * @code
  650. * return array(
  651. * CLIENT_ID,
  652. * CLIENT_SECRET
  653. * );
  654. * @endcode
  655. *
  656. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
  657. *
  658. * @ingroup oauth2_section_2
  659. */
  660. protected function getClientCredentials(array $inputData, array $authHeaders) {
  661. // Basic Authentication is used
  662. if (!empty($authHeaders['PHP_AUTH_USER'])) {
  663. return array($authHeaders['PHP_AUTH_USER'], $authHeaders['PHP_AUTH_PW']);
  664. } elseif (empty($inputData['client_id'])) { // No credentials were specified
  665. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'Client id was not found in the headers or body');
  666. } else {
  667. // This method is not recommended, but is supported by specification
  668. return array($inputData['client_id'], $inputData['client_secret']);
  669. }
  670. }
  671. // End-user/client Authorization (Section 2 of IETF Draft).
  672. /**
  673. * Pull the authorization request data out of the HTTP request.
  674. * - The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it
  675. * by setting CONFIG_ENFORCE_INPUT_REDIRECT to true.
  676. * - The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that
  677. * CSRF protection is MANDATORY. You can enforce this by setting the CONFIG_ENFORCE_STATE to true.
  678. *
  679. * @param $inputData - The draft specifies that the parameters should be
  680. * retrieved from GET, but you can override to whatever method you like.
  681. * @return
  682. * The authorization parameters so the authorization server can prompt
  683. * the user for approval if valid.
  684. *
  685. * @throws OAuth2ServerException
  686. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
  687. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12
  688. *
  689. * @ingroup oauth2_section_3
  690. */
  691. public function getAuthorizeParams(array $inputData = NULL) {
  692. $filters = array(
  693. "client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::CLIENT_ID_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
  694. "response_type" => array("flags" => FILTER_REQUIRE_SCALAR),
  695. "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
  696. "state" => array("flags" => FILTER_REQUIRE_SCALAR),
  697. "scope" => array("flags" => FILTER_REQUIRE_SCALAR)
  698. );
  699. if (!isset($inputData)) {
  700. $inputData = $_GET;
  701. }
  702. $input = filter_var_array($inputData, $filters);
  703. // Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI)
  704. if (!$input["client_id"]) {
  705. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "No client id supplied"); // We don't have a good URI to use
  706. }
  707. // Get client details
  708. $stored = $this->storage->getClientDetails($input["client_id"]);
  709. if ($stored === FALSE) {
  710. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "Client id does not exist");
  711. }
  712. // Make sure a valid redirect_uri was supplied. If specified, it must match the stored URI.
  713. // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2
  714. // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
  715. // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
  716. if (!$input["redirect_uri"] && !$stored["redirect_uri"]) {
  717. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'No redirect URL was supplied or stored.');
  718. }
  719. if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
  720. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI is mandatory and was not supplied.');
  721. }
  722. // Only need to validate if redirect_uri provided on input and stored.
  723. if ($stored["redirect_uri"] && $input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
  724. throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI provided is missing or does not match');
  725. }
  726. // Select the redirect URI
  727. $input["redirect_uri"] = isset($input["redirect_uri"]) ? $input["redirect_uri"] : $stored["redirect_uri"];
  728. // type and client_id are required
  729. if (!$input["response_type"]) {
  730. throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, 'Invalid or missing response type.', $input["state"]);
  731. }
  732. if ($input['response_type'] != self::RESPONSE_TYPE_AUTH_CODE && $input['response_type'] != self::RESPONSE_TYPE_ACCESS_TOKEN) {
  733. throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_UNSUPPORTED_RESPONSE_TYPE, NULL, $input["state"]);
  734. }
  735. // Validate that the requested scope is supported
  736. if ($input["scope"] && !$this->checkScope($input["scope"], $this->getVariable(self::CONFIG_SUPPORTED_SCOPES))) {
  737. throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.', $input["state"]);
  738. }
  739. // Validate state parameter exists (if configured to enforce this)
  740. if ($this->getVariable(self::CONFIG_ENFORCE_STATE) && !$input["state"]) {
  741. throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, "The state parameter is required.");
  742. }
  743. // Return retrieved client details together with input
  744. return ($input + $stored);
  745. }
  746. /**
  747. * Redirect the user appropriately after approval.
  748. *
  749. * After the user has approved or denied the access request the
  750. * authorization server should call this function to redirect the user
  751. * appropriately.
  752. *
  753. * @param $is_authorized
  754. * TRUE or FALSE depending on whether the user authorized the access.
  755. * @param $user_id
  756. * Identifier of user who authorized the client
  757. * @param $params
  758. * An associative array as below:
  759. * - response_type: The requested response: an access token, an
  760. * authorization code, or both.
  761. * - client_id: The client identifier as described in Section 2.
  762. * - redirect_uri: An absolute URI to which the authorization server
  763. * will redirect the user-agent to when the end-user authorization
  764. * step is completed.
  765. * - scope: (optional) The scope of the access request expressed as a
  766. * list of space-delimited strings.
  767. * - state: (optional) An opaque value used by the client to maintain
  768. * state between the request and callback.
  769. *
  770. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
  771. *
  772. * @ingroup oauth2_section_4
  773. */
  774. public function finishClientAuthorization($is_authorized, $user_id = NULL, $params = array()) {
  775. list($redirect_uri, $result) = $this->getAuthResult($is_authorized, $user_id, $params);
  776. $this->doRedirectUriCallback($redirect_uri, $result);
  777. }
  778. // same params as above
  779. public function getAuthResult($is_authorized, $user_id = NULL, $params = array()) {
  780. // We repeat this, because we need to re-validate. In theory, this could be POSTed
  781. // by a 3rd-party (because we are not internally enforcing NONCEs, etc)
  782. $params = $this->getAuthorizeParams($params);
  783. $params += array('scope' => NULL, 'state' => NULL);
  784. extract($params);
  785. if ($state !== NULL) {
  786. $result["query"]["state"] = $state;
  787. }
  788. if ($is_authorized === FALSE) {
  789. throw new OAuth2RedirectException($redirect_uri, self::ERROR_USER_DENIED, "The user denied access to your application", $state);
  790. } else {
  791. if ($response_type == self::RESPONSE_TYPE_AUTH_CODE) {
  792. $result["query"]["code"] = $this->createAuthCode($client_id, $user_id, $redirect_uri, $scope);
  793. } elseif ($response_type == self::RESPONSE_TYPE_ACCESS_TOKEN) {
  794. $result["fragment"] = $this->createAccessToken($client_id, $user_id, $scope);
  795. }
  796. }
  797. return array($redirect_uri, $result);
  798. }
  799. // Other/utility functions.
  800. /**
  801. * Redirect the user agent.
  802. *
  803. * Handle both redirect for success or error response.
  804. *
  805. * @param $redirect_uri
  806. * An absolute URI to which the authorization server will redirect
  807. * the user-agent to when the end-user authorization step is completed.
  808. * @param $params
  809. * Parameters to be pass though buildUri().
  810. *
  811. * @ingroup oauth2_section_4
  812. */
  813. private function doRedirectUriCallback($redirect_uri, $params) {
  814. header("HTTP/1.1 " . self::HTTP_FOUND);
  815. header("Location: " . $this->buildUri($redirect_uri, $params));
  816. exit();
  817. }
  818. /**
  819. * Build the absolute URI based on supplied URI and parameters.
  820. *
  821. * @param $uri
  822. * An absolute URI.
  823. * @param $params
  824. * Parameters to be append as GET.
  825. *
  826. * @return
  827. * An absolute URI with supplied parameters.
  828. *
  829. * @ingroup oauth2_section_4
  830. */
  831. private function buildUri($uri, $params) {
  832. $parse_url = parse_url($uri);
  833. // Add our params to the parsed uri
  834. foreach ( $params as $k => $v ) {
  835. if (isset($parse_url[$k])) {
  836. $parse_url[$k] .= "&" . http_build_query($v);
  837. } else {
  838. $parse_url[$k] = http_build_query($v);
  839. }
  840. }
  841. // Put humpty dumpty back together
  842. return
  843. ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
  844. . ((isset($parse_url["user"])) ? $parse_url["user"]
  845. . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
  846. . ((isset($parse_url["host"])) ? $parse_url["host"] : "")
  847. . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
  848. . ((isset($parse_url["path"])) ? $parse_url["path"] : "")
  849. . ((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "")
  850. . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "")
  851. ;
  852. }
  853. /**
  854. * Handle the creation of access token, also issue refresh token if support.
  855. *
  856. * This belongs in a separate factory, but to keep it simple, I'm just
  857. * keeping it here.
  858. *
  859. * @param $client_id
  860. * Client identifier related to the access token.
  861. * @param $scope
  862. * (optional) Scopes to be stored in space-separated string.
  863. *
  864. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5
  865. * @ingroup oauth2_section_5
  866. */
  867. protected function createAccessToken($client_id, $user_id, $scope = NULL) {
  868. $token = array(
  869. "access_token" => $this->genAccessToken(),
  870. "expires_in" => $this->getVariable(self::CONFIG_ACCESS_LIFETIME),
  871. "token_type" => $this->getVariable(self::CONFIG_TOKEN_TYPE),
  872. "scope" => $scope
  873. );
  874. $this->storage->setAccessToken($token["access_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_ACCESS_LIFETIME), $scope);
  875. // Issue a refresh token also, if we support them
  876. if ($this->storage instanceof IOAuth2RefreshTokens) {
  877. $token["refresh_token"] = $this->genAccessToken();
  878. $this->storage->setRefreshToken($token["refresh_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_REFRESH_LIFETIME), $scope);
  879. // If we've granted a new refresh token, expire the old one
  880. if ($this->oldRefreshToken) {
  881. $this->storage->unsetRefreshToken($this->oldRefreshToken);
  882. unset($this->oldRefreshToken);
  883. }
  884. }
  885. return $token;
  886. }
  887. /**
  888. * Handle the creation of auth code.
  889. *
  890. * This belongs in a separate factory, but to keep it simple, I'm just
  891. * keeping it here.
  892. *
  893. * @param $client_id
  894. * Client identifier related to the access token.
  895. * @param $redirect_uri
  896. * An absolute URI to which the authorization server will redirect the
  897. * user-agent to when the end-user authorization step is completed.
  898. * @param $scope
  899. * (optional) Scopes to be stored in space-separated string.
  900. *
  901. * @ingroup oauth2_section_4
  902. */
  903. private function createAuthCode($client_id, $user_id, $redirect_uri, $scope = NULL) {
  904. $code = $this->genAuthCode();
  905. $this->storage->setAuthCode($code, $client_id, $user_id, $redirect_uri, time() + $this->getVariable(self::CONFIG_AUTH_LIFETIME), $scope);
  906. return $code;
  907. }
  908. /**
  909. * Generates an unique access token.
  910. *
  911. * Implementing classes may want to override this function to implement
  912. * other access token generation schemes.
  913. *
  914. * @return
  915. * An unique access token.
  916. *
  917. * @ingroup oauth2_section_4
  918. * @see OAuth2::genAuthCode()
  919. */
  920. protected function genAccessToken() {
  921. $tokenLen = 40;
  922. if (file_exists('/dev/urandom')) { // Get 100 bytes of random data
  923. $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
  924. } else {
  925. $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
  926. }
  927. return substr(hash('sha512', $randomData), 0, $tokenLen);
  928. }
  929. /**
  930. * Generates an unique auth code.
  931. *
  932. * Implementing classes may want to override this function to implement
  933. * other auth code generation schemes.
  934. *
  935. * @return
  936. * An unique auth code.
  937. *
  938. * @ingroup oauth2_section_4
  939. * @see OAuth2::genAccessToken()
  940. */
  941. protected function genAuthCode() {
  942. return $this->genAccessToken(); // let's reuse the same scheme for token generation
  943. }
  944. /**
  945. * Pull out the Authorization HTTP header and return it.
  946. * According to draft 20, standard basic authorization is the only
  947. * header variable required (this does not apply to extended grant types).
  948. *
  949. * Implementing classes may need to override this function if need be.
  950. *
  951. * @todo We may need to re-implement pulling out apache headers to support extended grant types
  952. *
  953. * @return
  954. * An array of the basic username and password provided.
  955. *
  956. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
  957. * @ingroup oauth2_section_2
  958. */
  959. protected function getAuthorizationHeader() {
  960. return array(
  961. 'PHP_AUTH_USER' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
  962. 'PHP_AUTH_PW' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''
  963. );
  964. }
  965. /**
  966. * Send out HTTP headers for JSON.
  967. *
  968. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
  969. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
  970. *
  971. * @ingroup oauth2_section_5
  972. */
  973. private function sendJsonHeaders() {
  974. if (php_sapi_name() === 'cli' || headers_sent()) {
  975. return;
  976. }
  977. header("Content-Type: application/json");
  978. header("Cache-Control: no-store");
  979. }
  980. /**
  981. * Internal method for validating redirect URI supplied
  982. * @param string $inputUri
  983. * @param string $storedUri
  984. */
  985. protected function validateRedirectUri($inputUri, $storedUri) {
  986. if (!$inputUri || !$storedUri) {
  987. return false; // if either one is missing, assume INVALID
  988. }
  989. return strcasecmp(substr($inputUri, 0, strlen($storedUri)), $storedUri) === 0;
  990. }
  991. }