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