-
Notifications
You must be signed in to change notification settings - Fork 368
/
OpenIDConnectClient.php
2084 lines (1740 loc) · 66.9 KB
/
OpenIDConnectClient.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
/**
*
* Copyright MITRE 2020
*
* OpenIDConnectClient for PHP7+
* Author: Michael Jett <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
namespace Jumbojett;
use Error;
use Exception;
use phpseclib3\Crypt\RSA;
use phpseclib3\Math\BigInteger;
use stdClass;
use function bin2hex;
use function is_object;
use function random_bytes;
/**
* A wrapper around base64_decode which decodes Base64URL-encoded data,
* which is not the same alphabet as base64.
* @param string $base64url
* @return bool|string
*/
function base64url_decode(string $base64url) {
return base64_decode(b64url2b64($base64url));
}
/**
* Per RFC4648, "base64 encoding with URL-safe and filename-safe
* alphabet". This just replaces characters 62 and 63. None of the
* reference implementations seem to restore the padding if necessary,
* but we'll do it anyway.
* @param string $base64url
* @return string
*/
function b64url2b64(string $base64url): string
{
// "Shouldn't" be necessary, but why not
$padding = strlen($base64url) % 4;
if ($padding > 0) {
$base64url .= str_repeat('=', 4 - $padding);
}
return strtr($base64url, '-_', '+/');
}
/**
* OpenIDConnect Exception Class
*/
class OpenIDConnectClientException extends Exception
{
}
/**
*
* Please note this class stores nonces by default in $_SESSION['openid_connect_nonce']
*
*/
class OpenIDConnectClient
{
/**
* @var string arbitrary id value
*/
private $clientID;
/**
* @var string arbitrary name value
*/
private $clientName;
/**
* @var string arbitrary secret value
*/
private $clientSecret;
/**
* @var array holds the provider configuration
*/
private $providerConfig = [];
/**
* @var string http proxy if necessary
*/
private $httpProxy;
/**
* @var string full system path to the SSL certificate
*/
private $certPath;
/**
* @var bool Verify SSL peer on transactions
*/
private $verifyPeer = true;
/**
* @var bool Verify peer hostname on transactions
*/
private $verifyHost = true;
/**
* @var string if we acquire an access token it will be stored here
*/
protected $accessToken;
/**
* @var string if we acquire a refresh token it will be stored here
*/
private $refreshToken;
/**
* @var string if we acquire an id token it will be stored here
*/
protected $idToken;
/**
* @var object stores the token response
*/
private $tokenResponse;
/**
* @var array holds scopes
*/
private $scopes = [];
/**
* @var int|null Response code from the server
*/
protected $responseCode;
/**
* @var string|null Content type from the server
*/
protected $responseContentType;
/**
* @var array holds response types
*/
private $responseTypes = [];
/**
* @var array holds authentication parameters
*/
private $authParams = [];
/**
* @var array holds additional registration parameters for example post_logout_redirect_uris
*/
private $registrationParams = [];
/**
* @var mixed holds well-known openid server properties
*/
private $wellKnown = false;
/**
* @var mixed holds well-known openid configuration parameters, like policy for MS Azure AD B2C User Flow
* @see https://docs.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview
*/
private $wellKnownConfigParameters = [];
/**
* @var int timeout (seconds)
*/
protected $timeOut = 60;
/**
* @var int leeway (seconds)
*/
private $leeway = 300;
/**
* @var array holds response types
*/
private $additionalJwks = [];
/**
* @var object holds verified jwt claims
*/
protected $verifiedClaims = [];
/**
* @var callable|null validator function for issuer claim
*/
private $issuerValidator;
/**
* @var callable|null generator function for private key jwt client authentication
*/
private $privateKeyJwtGenerator;
/**
* @var bool Allow OAuth 2 implicit flow; see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth
*/
private $allowImplicitFlow = false;
/**
* @var string
*/
private $redirectURL;
/**
* @var int defines which URL-encoding http_build_query() uses
*/
protected $encType = PHP_QUERY_RFC1738;
/**
* @var bool Enable or disable upgrading to HTTPS by paying attention to HTTP header HTTP_UPGRADE_INSECURE_REQUESTS
*/
protected $httpUpgradeInsecureRequests = true;
/**
* @var string holds code challenge method for PKCE mode
* @see https://tools.ietf.org/html/rfc7636
*/
private $codeChallengeMethod = false;
/**
* @var array holds PKCE supported algorithms
*/
private $pkceAlgs = ['S256' => 'sha256', 'plain' => false];
/**
* @var string if we acquire a sid in back-channel logout it will be stored here
*/
private $backChannelSid;
/**
* @var string if we acquire a sub in back-channel logout it will be stored here
*/
private $backChannelSubject;
/**
* @var array list of supported auth methods
*/
private $token_endpoint_auth_methods_supported = ['client_secret_basic'];
/**
* @param string|null $provider_url optional
* @param string|null $client_id optional
* @param string|null $client_secret optional
* @param string|null $issuer
*/
public function __construct(string $provider_url = null, string $client_id = null, string $client_secret = null, string $issuer = null) {
$this->setProviderURL($provider_url);
if ($issuer === null) {
$this->setIssuer($provider_url);
} else {
$this->setIssuer($issuer);
}
$this->clientID = $client_id;
$this->clientSecret = $client_secret;
}
/**
* @param $provider_url
*/
public function setProviderURL($provider_url) {
$this->providerConfig['providerUrl'] = $provider_url;
}
/**
* @param $issuer
*/
public function setIssuer($issuer) {
$this->providerConfig['issuer'] = $issuer;
}
/**
* @param $response_types
*/
public function setResponseTypes($response_types) {
$this->responseTypes = array_merge($this->responseTypes, (array)$response_types);
}
/**
* @return bool
* @throws OpenIDConnectClientException
*/
public function authenticate(): bool
{
// Do a preemptive check to see if the provider has thrown an error from a previous redirect
if (isset($_REQUEST['error'])) {
$desc = isset($_REQUEST['error_description']) ? ' Description: ' . $_REQUEST['error_description'] : '';
throw new OpenIDConnectClientException('Error: ' . $_REQUEST['error'] .$desc);
}
// If we have an authorization code then proceed to request a token
if (isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$token_json = $this->requestTokens($code);
// Throw an error if the server returns one
if (isset($token_json->error)) {
if (isset($token_json->error_description)) {
throw new OpenIDConnectClientException($token_json->error_description);
}
throw new OpenIDConnectClientException('Got response: ' . $token_json->error);
}
// Do an OpenID Connect session check
if (!isset($_REQUEST['state']) || ($_REQUEST['state'] !== $this->getState())) {
throw new OpenIDConnectClientException('Unable to determine state');
}
// Cleanup state
$this->unsetState();
if (!property_exists($token_json, 'id_token')) {
throw new OpenIDConnectClientException('User did not authorize openid scope.');
}
$id_token = $token_json->id_token;
$idTokenHeaders = $this->decodeJWT($id_token);
if (isset($idTokenHeaders->enc)) {
// Handle JWE
$id_token = $this->handleJweResponse($id_token);
}
$claims = $this->decodeJWT($id_token, 1);
// Verify the signature
$this->verifySignatures($id_token);
// Save the id token
$this->idToken = $id_token;
// Save the access token
$this->accessToken = $token_json->access_token;
// If this is a valid claim
if ($this->verifyJWTClaims($claims, $token_json->access_token)) {
// Clean up the session a little
$this->unsetNonce();
// Save the full response
$this->tokenResponse = $token_json;
// Save the verified claims
$this->verifiedClaims = $claims;
// Save the refresh token, if we got one
if (isset($token_json->refresh_token)) {
$this->refreshToken = $token_json->refresh_token;
}
// Success!
return true;
}
throw new OpenIDConnectClientException ('Unable to verify JWT claims');
}
if ($this->allowImplicitFlow && isset($_REQUEST['id_token'])) {
// if we have no code but an id_token use that
$id_token = $_REQUEST['id_token'];
$accessToken = $_REQUEST['access_token'] ?? null;
// Do an OpenID Connect session check
if (!isset($_REQUEST['state']) || ($_REQUEST['state'] !== $this->getState())) {
throw new OpenIDConnectClientException('Unable to determine state');
}
// Cleanup state
$this->unsetState();
$claims = $this->decodeJWT($id_token, 1);
// Verify the signature
$this->verifySignatures($id_token);
// Save the id token
$this->idToken = $id_token;
// If this is a valid claim
if ($this->verifyJWTClaims($claims, $accessToken)) {
// Clean up the session a little
$this->unsetNonce();
// Save the verified claims
$this->verifiedClaims = $claims;
// Save the access token
if ($accessToken) {
$this->accessToken = $accessToken;
}
// Success!
return true;
}
throw new OpenIDConnectClientException ('Unable to verify JWT claims');
}
$this->requestAuthorization();
return false;
}
/**
* It calls the end-session endpoint of the OpenID Connect provider to notify the OpenID
* Connect provider that the end-user has logged out of the relying party site
* (the client application).
*
* @param string $idToken ID token (obtained at login)
* @param string|null $redirect URL to which the RP is requesting that the End-User's User Agent
* be redirected after a logout has been performed. The value MUST have been previously
* registered with the OP. Value can be null.
*
* @throws OpenIDConnectClientException
*/
public function signOut(string $idToken, $redirect) {
$sign_out_endpoint = $this->getProviderConfigValue('end_session_endpoint');
if($redirect === null){
$signout_params = ['id_token_hint' => $idToken];
}
else {
$signout_params = [
'id_token_hint' => $idToken,
'post_logout_redirect_uri' => $redirect];
}
$sign_out_endpoint .= (strpos($sign_out_endpoint, '?') === false ? '?' : '&') . http_build_query( $signout_params, '', '&', $this->encType);
$this->redirect($sign_out_endpoint);
}
/**
* Decode and then verify a logout token sent as part of
* back-channel logout flows.
*
* This function should be evaluated as a boolean check
* in your route that receives the POST request for back-channel
* logout executed from the OP.
*
* @return bool
* @throws OpenIDConnectClientException
*/
public function verifyLogoutToken(): bool
{
if (isset($_REQUEST['logout_token'])) {
$logout_token = $_REQUEST['logout_token'];
$claims = $this->decodeJWT($logout_token, 1);
// Verify the signature
$this->verifySignatures($logout_token);
// Verify Logout Token Claims
if ($this->verifyLogoutTokenClaims($claims)) {
$this->verifiedClaims = $claims;
return true;
}
return false;
}
throw new OpenIDConnectClientException('Back-channel logout: There was no logout_token in the request');
}
/**
* Verify each claim in the logout token according to the
* spec for back-channel logout.
*
* @param object $claims
* @return bool
* @throws OpenIDConnectClientException
*/
public function verifyLogoutTokenClaims($claims): bool
{
// Verify that the Logout Token doesn't contain a nonce Claim.
if (isset($claims->nonce)) {
return false;
}
// Verify that the logout token contains a sub or sid, or both
if (!isset($claims->sid) && !isset($claims->sub)) {
return false;
}
// Set the sid, which could be used to map to a session in
// the RP, and therefore be used to help destroy the RP's
// session.
if (isset($claims->sid)) {
$this->backChannelSid = $claims->sid;
}
// Set the sub, which could be used to map to a session in
// the RP, and therefore be used to help destroy the RP's
// session.
if (isset($claims->sub)) {
$this->backChannelSubject = $claims->sub;
}
// Verify that the Logout Token contains an events Claim whose
// value is a JSON object containing the member name
// http://schemas.openid.net/event/backchannel-logout
if (isset($claims->events)) {
$events = (array) $claims->events;
if (!isset($events['http://schemas.openid.net/event/backchannel-logout']) ||
!is_object($events['http://schemas.openid.net/event/backchannel-logout'])) {
return false;
}
}
// Validate the iss
if (!$this->validateIssuer($claims->iss)) {
return false;
}
// Validate the aud
$auds = $claims->aud;
$auds = is_array( $auds ) ? $auds : [ $auds ];
if (!in_array($this->clientID, $auds, true)) {
return false;
}
// Validate the iat. At this point we can return true if it is ok
if (isset($claims->iat) && ((is_int($claims->iat)) && ($claims->iat <= time() + $this->leeway))) {
return true;
}
return false;
}
/**
* @param array $scope - example: openid, given_name, etc...
*/
public function addScope(array $scope) {
$this->scopes = array_merge($this->scopes, $scope);
}
/**
* @param array $param - example: prompt=login
*/
public function addAuthParam(array $param) {
$this->authParams = array_merge($this->authParams, $param);
}
/**
* @param array $param - example: post_logout_redirect_uris=[http://example.com/successful-logout]
*/
public function addRegistrationParam(array $param) {
$this->registrationParams = array_merge($this->registrationParams, $param);
}
public function setTokenEndpointAuthMethodsSupported(array $token_endpoint_auth_methods_supported)
{
$this->token_endpoint_auth_methods_supported = $token_endpoint_auth_methods_supported;
}
/**
* @param $jwk object - example: (object) ['kid' => ..., 'nbf' => ..., 'use' => 'sig', 'kty' => "RSA", 'e' => "", 'n' => ""]
*/
protected function addAdditionalJwk($jwk) {
$this->additionalJwks[] = $jwk;
}
/**
* Gets anything that we need configuration wise including endpoints, and other values
*
* @param string $param
* @param string|string[]|bool|null $default optional
* @return string|string[]|bool
*
* @throws OpenIDConnectClientException
*/
protected function getProviderConfigValue(string $param, $default = null)
{
// If the configuration value is not available, attempt to fetch it from a well known config endpoint
// This is also known as auto "discovery"
if (!isset($this->providerConfig[$param])) {
$this->providerConfig[$param] = $this->getWellKnownConfigValue($param, $default);
}
return $this->providerConfig[$param];
}
/**
* Gets anything that we need configuration wise including endpoints, and other values
*
* @param string $param
* @param string|string[]|bool|null $default optional
* @return string|string[]|bool
*
* @throws OpenIDConnectClientException
*/
protected function getWellKnownConfigValue(string $param, $default = null)
{
// If the configuration value is not available, attempt to fetch it from a well known config endpoint
// This is also known as auto "discovery"
if(!$this->wellKnown) {
$well_known_config_url = rtrim($this->getProviderURL(), '/') . '/.well-known/openid-configuration';
if (count($this->wellKnownConfigParameters) > 0){
$well_known_config_url .= '?' . http_build_query($this->wellKnownConfigParameters) ;
}
$this->wellKnown = json_decode($this->fetchURL($well_known_config_url), false);
}
$value = $this->wellKnown->{$param} ?? false;
if ($value) {
return $value;
}
if (isset($default)) {
// Uses default value if provided
return $default;
}
throw new OpenIDConnectClientException("The provider $param could not be fetched. Make sure your provider has a well known configuration available.");
}
/**
* Set optional parameters for .well-known/openid-configuration
*/
public function setWellKnownConfigParameters(array $params = []){
$this->wellKnownConfigParameters=$params;
}
/**
* @param string $url Sets redirect URL for auth flow
*/
public function setRedirectURL(string $url) {
if (parse_url($url,PHP_URL_HOST) !== false) {
$this->redirectURL = $url;
}
}
/**
* Gets the URL of the current page we are on, encodes, and returns it
*
* @return string
*/
public function getRedirectURL(): string
{
// If the redirect URL has been set then return it.
if (property_exists($this, 'redirectURL') && $this->redirectURL) {
return $this->redirectURL;
}
// Other-wise return the URL of the current page
/**
* Thank you
* http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server
*/
/*
* Compatibility with multiple host headers.
* The problem with SSL over port 80 is resolved and non-SSL over port 443.
* Support of 'ProxyReverse' configurations.
*/
if ($this->httpUpgradeInsecureRequests && isset($_SERVER['HTTP_UPGRADE_INSECURE_REQUESTS']) && ($_SERVER['HTTP_UPGRADE_INSECURE_REQUESTS'] === '1')) {
$protocol = 'https';
} elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$protocol = $_SERVER['HTTP_X_FORWARDED_PROTO'];
} elseif (isset($_SERVER['REQUEST_SCHEME'])) {
$protocol = $_SERVER['REQUEST_SCHEME'];
} elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$protocol = 'https';
} else {
$protocol = 'http';
}
if (isset($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$port = (int)$_SERVER['HTTP_X_FORWARDED_PORT'];
} elseif (isset($_SERVER['SERVER_PORT'])) {
# keep this case - even if some tool claim it is unnecessary
$port = (int)$_SERVER['SERVER_PORT'];
} elseif ($protocol === 'https') {
$port = 443;
} else {
$port = 80;
}
if (isset($_SERVER['HTTP_HOST'])) {
$host = explode(':', $_SERVER['HTTP_HOST'])[0];
} elseif (isset($_SERVER['SERVER_NAME'])) {
$host = $_SERVER['SERVER_NAME'];
} elseif (isset($_SERVER['SERVER_ADDR'])) {
$host = $_SERVER['SERVER_ADDR'];
} else {
return 'http:///';
}
$port = (443 === $port) || (80 === $port) ? '' : ':' . $port;
$explodedRequestUri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI']) : [];
return sprintf('%s://%s%s/%s', $protocol, $host, $port, trim(reset($explodedRequestUri), '/'));
}
/**
* Used for arbitrary value generation for nonces and state
*
* @return string
* @throws OpenIDConnectClientException
*/
protected function generateRandString(): string
{
try {
return bin2hex(random_bytes(16));
} catch (Error $e) {
throw new OpenIDConnectClientException('Random token generation failed.');
} catch (Exception $e) {
throw new OpenIDConnectClientException('Random token generation failed.');
}
}
/**
* Start Here
* @return void
* @throws OpenIDConnectClientException
* @throws Exception
*/
private function requestAuthorization() {
$auth_endpoint = $this->getProviderConfigValue('authorization_endpoint');
$response_type = 'code';
// Generate and store a nonce in the session
// The nonce is an arbitrary value
$nonce = $this->setNonce($this->generateRandString());
// State essentially acts as a session key for OIDC
$state = $this->setState($this->generateRandString());
$auth_params = array_merge($this->authParams, [
'response_type' => $response_type,
'redirect_uri' => $this->getRedirectURL(),
'client_id' => $this->clientID,
'nonce' => $nonce,
'state' => $state,
'scope' => 'openid'
]);
// If the client has been registered with additional scopes
if (count($this->scopes) > 0) {
$auth_params = array_merge($auth_params, ['scope' => implode(' ', array_merge($this->scopes, ['openid']))]);
}
// If the client has been registered with additional response types
if (count($this->responseTypes) > 0) {
$auth_params = array_merge($auth_params, ['response_type' => implode(' ', $this->responseTypes)]);
}
// If the client supports Proof Key for Code Exchange (PKCE)
$codeChallengeMethod = $this->getCodeChallengeMethod();
if (!empty($codeChallengeMethod) && in_array($codeChallengeMethod, $this->getProviderConfigValue('code_challenge_methods_supported', []), true)) {
$codeVerifier = bin2hex(random_bytes(64));
$this->setCodeVerifier($codeVerifier);
if (!empty($this->pkceAlgs[$codeChallengeMethod])) {
$codeChallenge = rtrim(strtr(base64_encode(hash($this->pkceAlgs[$codeChallengeMethod], $codeVerifier, true)), '+/', '-_'), '=');
} else {
$codeChallenge = $codeVerifier;
}
$auth_params = array_merge($auth_params, [
'code_challenge' => $codeChallenge,
'code_challenge_method' => $codeChallengeMethod
]);
}
$auth_endpoint .= (strpos($auth_endpoint, '?') === false ? '?' : '&') . http_build_query($auth_params, '', '&', $this->encType);
$this->commitSession();
$this->redirect($auth_endpoint);
}
/**
* Requests a client credentials token
*
* @throws OpenIDConnectClientException
*/
public function requestClientCredentialsToken() {
$token_endpoint = $this->getProviderConfigValue('token_endpoint');
$headers = [];
$grant_type = 'client_credentials';
$post_data = [
'grant_type' => $grant_type,
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret,
'scope' => implode(' ', $this->scopes)
];
// Convert token params to string format
$post_params = http_build_query($post_data, '', '&', $this->encType);
return json_decode($this->fetchURL($token_endpoint, $post_params, $headers), false);
}
/**
* Requests a resource owner token
* (Defined in https://tools.ietf.org/html/rfc6749#section-4.3)
*
* @param boolean $bClientAuth Indicates that the Client ID and Secret be used for client authentication
* @return mixed
* @throws OpenIDConnectClientException
*/
public function requestResourceOwnerToken(bool $bClientAuth = false) {
$token_endpoint = $this->getProviderConfigValue('token_endpoint');
$headers = [];
$grant_type = 'password';
$post_data = [
'grant_type' => $grant_type,
'username' => $this->authParams['username'],
'password' => $this->authParams['password'],
'scope' => implode(' ', $this->scopes)
];
//For client authentication include the client values
if($bClientAuth) {
$token_endpoint_auth_methods_supported = $this->getProviderConfigValue('token_endpoint_auth_methods_supported', ['client_secret_basic']);
if ($this->supportsAuthMethod('client_secret_basic', $token_endpoint_auth_methods_supported)) {
$headers = ['Authorization: Basic ' . base64_encode(urlencode($this->clientID) . ':' . urlencode($this->clientSecret))];
} else {
$post_data['client_id'] = $this->clientID;
$post_data['client_secret'] = $this->clientSecret;
}
}
// Convert token params to string format
$post_params = http_build_query($post_data, '', '&', $this->encType);
return json_decode($this->fetchURL($token_endpoint, $post_params, $headers), false);
}
/**
* Requests ID and Access tokens
*
* @param string $code
* @param string[] $headers Extra HTTP headers to pass to the token endpoint
* @return mixed
* @throws OpenIDConnectClientException
*/
protected function requestTokens(string $code, array $headers = []) {
$token_endpoint = $this->getProviderConfigValue('token_endpoint');
$token_endpoint_auth_methods_supported = $this->getProviderConfigValue('token_endpoint_auth_methods_supported', ['client_secret_basic']);
$grant_type = 'authorization_code';
$token_params = [
'grant_type' => $grant_type,
'code' => $code,
'redirect_uri' => $this->getRedirectURL(),
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret
];
$authorizationHeader = null;
# Consider Basic authentication if provider config is set this way
if ($this->supportsAuthMethod('client_secret_basic', $token_endpoint_auth_methods_supported)) {
$authorizationHeader = 'Authorization: Basic ' . base64_encode(urlencode($this->clientID) . ':' . urlencode($this->clientSecret));
unset($token_params['client_secret'], $token_params['client_id']);
}
// When there is a private key jwt generator, and it is supported then use it as client authentication
if ($this->privateKeyJwtGenerator !== null && $this->supportsAuthMethod('private_key_jwt', $token_endpoint_auth_methods_supported)) {
$token_params['client_assertion_type'] = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
$token_params['client_assertion'] = $this->privateKeyJwtGenerator->__invoke($token_endpoint);
}
if ($this->supportsAuthMethod('client_secret_jwt', $token_endpoint_auth_methods_supported)) {
$client_assertion_type = $this->getProviderConfigValue('client_assertion_type');
if(isset($this->providerConfig['client_assertion'])){
$client_assertion = $this->getProviderConfigValue('client_assertion');
}
else{
$client_assertion = $this->getJWTClientAssertion($this->getProviderConfigValue('token_endpoint'));
}
$token_params['client_assertion_type'] = $client_assertion_type;
$token_params['client_assertion'] = $client_assertion;
unset($token_params['client_secret']);
}
$ccm = $this->getCodeChallengeMethod();
$cv = $this->getCodeVerifier();
if (!empty($ccm) && !empty($cv)) {
$cs = $this->getClientSecret();
if (empty($cs)) {
$authorizationHeader = null;
unset($token_params['client_secret']);
}
$token_params = array_merge($token_params, [
'client_id' => $this->clientID,
'code_verifier' => $this->getCodeVerifier()
]);
}
// Convert token params to string format
$token_params = http_build_query($token_params, '', '&', $this->encType);
if (null !== $authorizationHeader) {
$headers[] = $authorizationHeader;
}
$this->tokenResponse = json_decode($this->fetchURL($token_endpoint, $token_params, $headers), false);
return $this->tokenResponse;
}
/**
* Request RFC8693 Token Exchange
* https://datatracker.ietf.org/doc/html/rfc8693
*
* @param string $subjectToken
* @param string $subjectTokenType
* @param string $audience
* @return mixed
* @throws OpenIDConnectClientException
*/
public function requestTokenExchange(string $subjectToken, string $subjectTokenType, string $audience = '') {
$token_endpoint = $this->getProviderConfigValue('token_endpoint');
$token_endpoint_auth_methods_supported = $this->getProviderConfigValue('token_endpoint_auth_methods_supported', ['client_secret_basic']);
$headers = [];
$grant_type = 'urn:ietf:params:oauth:grant-type:token-exchange';
$post_data = array(
'grant_type' => $grant_type,
'subject_token_type' => $subjectTokenType,
'subject_token' => $subjectToken,
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret,
'scope' => implode(' ', $this->scopes)
);
if (!empty($audience)) {
$post_data['audience'] = $audience;
}
# Consider Basic authentication if provider config is set this way
if ($this->supportsAuthMethod('client_secret_basic', $token_endpoint_auth_methods_supported)) {
$headers = ['Authorization: Basic ' . base64_encode(urlencode($this->clientID) . ':' . urlencode($this->clientSecret))];
unset($post_data['client_secret'], $post_data['client_id']);
}
// Convert token params to string format
$post_params = http_build_query($post_data, null, '&', $this->encType);
return json_decode($this->fetchURL($token_endpoint, $post_params, $headers), false);
}
/**
* Requests Access token with refresh token
*
* @param string $refresh_token
* @return mixed
* @throws OpenIDConnectClientException
*/
public function refreshToken(string $refresh_token) {
$token_endpoint = $this->getProviderConfigValue('token_endpoint');
$token_endpoint_auth_methods_supported = $this->getProviderConfigValue('token_endpoint_auth_methods_supported', ['client_secret_basic']);
$headers = [];
$grant_type = 'refresh_token';
$token_params = [
'grant_type' => $grant_type,
'refresh_token' => $refresh_token,
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret,
'scope' => implode(' ', $this->scopes),
];
# Consider Basic authentication if provider config is set this way
if ($this->supportsAuthMethod('client_secret_basic', $token_endpoint_auth_methods_supported)) {