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