Passed
Push — master ( 647dc2...e0ff36 )
by Rutger
02:57
created

Oauth2Module::getRequestOauthClaim()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
/**
4
 * @link http://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license http://www.yiiframework.com/license/
7
 */
8
9
namespace rhertogh\Yii2Oauth2Server;
10
11
use Defuse\Crypto\Exception\BadFormatException;
12
use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
13
use GuzzleHttp\Psr7\Response as Psr7Response;
14
use GuzzleHttp\Psr7\ServerRequest as Psr7ServerRequest;
15
use League\OAuth2\Server\CryptKey;
16
use League\OAuth2\Server\Grant\GrantTypeInterface;
17
use rhertogh\Yii2Oauth2Server\base\Oauth2BaseModule;
18
use rhertogh\Yii2Oauth2Server\components\server\tokens\Oauth2AccessTokenData;
19
use rhertogh\Yii2Oauth2Server\controllers\console\Oauth2ClientController;
20
use rhertogh\Yii2Oauth2Server\controllers\console\Oauth2DebugController;
21
use rhertogh\Yii2Oauth2Server\controllers\console\Oauth2EncryptionController;
22
use rhertogh\Yii2Oauth2Server\controllers\console\Oauth2MigrationsController;
23
use rhertogh\Yii2Oauth2Server\controllers\console\Oauth2PersonalAccessTokenController;
24
use rhertogh\Yii2Oauth2Server\exceptions\Oauth2ServerException;
25
use rhertogh\Yii2Oauth2Server\helpers\DiHelper;
26
use rhertogh\Yii2Oauth2Server\helpers\Psr7Helper;
27
use rhertogh\Yii2Oauth2Server\interfaces\components\authorization\Oauth2ClientAuthorizationRequestInterface;
28
use rhertogh\Yii2Oauth2Server\interfaces\components\encryption\Oauth2EncryptorInterface;
29
use rhertogh\Yii2Oauth2Server\interfaces\components\factories\encryption\Oauth2EncryptionKeyFactoryInterface;
30
use rhertogh\Yii2Oauth2Server\interfaces\components\factories\grants\base\Oauth2GrantTypeFactoryInterface;
31
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\scope\Oauth2OidcScopeCollectionInterface;
32
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\server\Oauth2OidcBearerTokenResponseInterface;
33
use rhertogh\Yii2Oauth2Server\interfaces\components\server\Oauth2AuthorizationServerInterface;
34
use rhertogh\Yii2Oauth2Server\interfaces\components\server\Oauth2ResourceServerInterface;
35
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\Oauth2CertificatesControllerInterface;
36
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\Oauth2ConsentControllerInterface;
37
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\Oauth2OidcControllerInterface;
38
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\Oauth2ServerControllerInterface;
39
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\Oauth2WellKnownControllerInterface;
40
use rhertogh\Yii2Oauth2Server\interfaces\filters\auth\Oauth2HttpBearerAuthInterface;
41
use rhertogh\Yii2Oauth2Server\interfaces\models\base\Oauth2EncryptedStorageInterface;
42
use rhertogh\Yii2Oauth2Server\interfaces\models\external\user\Oauth2OidcUserInterface;
43
use rhertogh\Yii2Oauth2Server\interfaces\models\external\user\Oauth2UserInterface;
44
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface;
45
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientScopeInterface;
46
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ScopeInterface;
47
use Yii;
48
use yii\base\BootstrapInterface;
49
use yii\base\InvalidArgumentException;
50
use yii\base\InvalidCallException;
51
use yii\base\InvalidConfigException;
52
use yii\console\Application as ConsoleApplication;
53
use yii\helpers\ArrayHelper;
54
use yii\helpers\Json;
55
use yii\helpers\StringHelper;
56
use yii\i18n\PhpMessageSource;
57
use yii\web\Application as WebApplication;
58
use yii\web\GroupUrlRule;
59
use yii\web\IdentityInterface;
60
use yii\web\Response;
61
use yii\web\UrlRule;
62
63
/**
64
 * This is the main module class for the Yii2 Oauth2 Server module.
65
 * To use it, include it as a module in the application configuration like the following:
66
 *
67
 * ~~~
68
 * return [
69
 *     'bootstrap' => ['oauth2'],
70
 *     'modules' => [
71
 *         'oauth2' => [
72
 *             'class' => 'rhertogh\Yii2Oauth2Server\Oauth2Module',
73
 *             // ... Please check docs/guide/start-installation.md further details
74
 *          ],
75
 *     ],
76
 * ]
77
 * ~~~
78
 *
79
 * @since 1.0.0
80
 */
81
class Oauth2Module extends Oauth2BaseModule implements BootstrapInterface
82
{
83
    /**
84
     * Application type "web": http response.
85
     * @since 1.0.0
86
     */
87
    public const APPLICATION_TYPE_WEB = 'web';
88
    /**
89
     * Application type "console": cli response.
90
     * @since 1.0.0
91
     */
92
    public const APPLICATION_TYPE_CONSOLE = 'console';
93
    /**
94
     * Supported Application types.
95
     * @since 1.0.0
96
     */
97
    public const APPLICATION_TYPES = [
98
        self::APPLICATION_TYPE_WEB,
99
        self::APPLICATION_TYPE_CONSOLE,
100
    ];
101
102
    /**
103
     * "Authorization Server" Role, please see guide for details.
104
     * @since 1.0.0
105
     */
106
    public const SERVER_ROLE_AUTHORIZATION_SERVER = 1;
107
    /**
108
     * "Resource Server" Role, please see guide for details.
109
     * @since 1.0.0
110
     */
111
    public const SERVER_ROLE_RESOURCE_SERVER = 2;
112
113
    /**
114
     * Required settings when the server role includes Authorization Server
115
     * @since 1.0.0
116
     */
117
    protected const REQUIRED_SETTINGS_AUTHORIZATION_SERVER = [
118
        'codesEncryptionKey',
119
        'storageEncryptionKeys',
120
        'defaultStorageEncryptionKey',
121
        'privateKey',
122
        'publicKey',
123
    ];
124
125
    /**
126
     * Encrypted Models
127
     *
128
     * @since 1.0.0
129
     */
130
    protected const ENCRYPTED_MODELS = [
131
        Oauth2ClientInterface::class,
132
    ];
133
134
    /**
135
     * Required settings when the server role includes Resource Server
136
     * @since 1.0.0
137
     */
138
    protected const REQUIRED_SETTINGS_RESOURCE_SERVER = [
139
        'publicKey',
140
    ];
141
142
    /**
143
     * Prefix used in session storage of Client Authorization Requests
144
     * @since 1.0.0
145
     */
146
    protected const CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX = 'OATH2_CLIENT_AUTHORIZATION_REQUEST_';
147
148
    /**
149
     * Controller mapping for the module. Will be parsed on `init()`.
150
     * @since 1.0.0
151
     */
152
    protected const CONTROLLER_MAP = [
153
        self::APPLICATION_TYPE_WEB => [
154
            Oauth2ServerControllerInterface::CONTROLLER_NAME => [
155
                'controller' => Oauth2ServerControllerInterface::class,
156
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
157
            ],
158
            Oauth2ConsentControllerInterface::CONTROLLER_NAME => [
159
                'controller' => Oauth2ConsentControllerInterface::class,
160
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
161
            ],
162
            Oauth2WellKnownControllerInterface::CONTROLLER_NAME => [
163
                'controller' => Oauth2WellKnownControllerInterface::class,
164
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
165
            ],
166
            Oauth2CertificatesControllerInterface::CONTROLLER_NAME => [
167
                'controller' => Oauth2CertificatesControllerInterface::class,
168
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
169
            ],
170
            Oauth2OidcControllerInterface::CONTROLLER_NAME => [
171
                'controller' => Oauth2OidcControllerInterface::class,
172
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
173
            ],
174
        ],
175
        self::APPLICATION_TYPE_CONSOLE => [
176
            'migrations' => [
177
                'controller' => Oauth2MigrationsController::class,
178
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER | self::SERVER_ROLE_RESOURCE_SERVER,
179
            ],
180
            'client' => [
181
                'controller' => Oauth2ClientController::class,
182
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
183
            ],
184
            'encryption' => [
185
                'controller' => Oauth2EncryptionController::class,
186
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
187
            ],
188
            'debug' => [
189
                'controller' => Oauth2DebugController::class,
190
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER | self::SERVER_ROLE_RESOURCE_SERVER,
191
            ],
192
            'pat' => [
193
                'controller' => Oauth2PersonalAccessTokenController::class,
194
                'serverRole' => self::SERVER_ROLE_AUTHORIZATION_SERVER,
195
            ]
196
        ]
197
    ];
198
199
    /**
200
     * @inheritdoc
201
     */
202
    public $controllerNamespace = __NAMESPACE__ . '\-'; // Set explicitly via $controllerMap in `init()`.
203
204
    /**
205
     * @var string|null The application type. If `null` the type will be automatically detected.
206
     * @see APPLICATION_TYPES
207
     */
208
    public $appType = null;
209
210
    /**
211
     * @var int The Oauth 2.0 Server Roles the module will perform.
212
     * @since 1.0.0
213
     */
214
    public $serverRole = self::SERVER_ROLE_AUTHORIZATION_SERVER | self::SERVER_ROLE_RESOURCE_SERVER;
215
216
    /**
217
     * @var string|null The private key for the server. Can be a string containing the key itself or point to a file.
218
     * When pointing to a file it's recommended to use an absolute path prefixed with 'file://' or start with
219
     * '@' to use a Yii path alias.
220
     * @see $privateKeyPassphrase For setting a passphrase for the private key.
221
     * @since 1.0.0
222
     */
223
    public $privateKey = null;
224
225
    /**
226
     * @var string|null The passphrase for the private key.
227
     * @since 1.0.0
228
     */
229
    public $privateKeyPassphrase = null;
230
    /**
231
     * @var string|null The public key for the server. Can be a string containing the key itself or point to a file.
232
     * When pointing to a file it's recommended to use an absolute path prefixed with 'file://' or start with
233
     * '@' to use a Yii path alias.
234
     * @since 1.0.0
235
     */
236
    public $publicKey = null;
237
238
    /**
239
     * @var string|null The encryption key for authorization and refresh codes.
240
     * @since 1.0.0
241
     */
242
    public $codesEncryptionKey = null;
243
244
    /**
245
     * @var string[]|string|null The encryption keys for storage like client secrets.
246
     * Where the array key is the name of the key, and the value the key itself. E.g.
247
     * `['2022-01-01' => 'def00000cb36fd6ed6641e0ad70805b28d....']`
248
     * If a string (instead of an array of strings) is specified it will be JSON decoded
249
     * it should contain an object where each property name is the name of the key, its value the key itself. E.g.
250
     * `{"2022-01-01": "def00000cb36fd6ed6641e0ad70805b28d...."}`
251
     *
252
     * @since 1.0.0
253
     */
254
    public $storageEncryptionKeys = null;
255
256
    /**
257
     * @var string|null The index of the default key in storageEncryptionKeys. E.g. 'myKey'.
258
     * @since 1.0.0
259
     */
260
    public $defaultStorageEncryptionKey = null;
261
262
    /**
263
     * @var class-string<Oauth2UserInterface>|null The Identity Class of your application,
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<Oauth2UserInterface>|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<Oauth2UserInterface>|null.
Loading history...
264
     * most likely the same as the 'identityClass' of your application's User Component.
265
     * @since 1.0.0
266
     */
267
    public $identityClass = null;
268
269
    /**
270
     * @var null|string Prefix used for url rules. When `null` the module's uniqueId will be used.
271
     * @since 1.0.0
272
     */
273
    public $urlRulesPrefix = null;
274
275
    /**
276
     * @var string URL path for the access token endpoint (will be prefixed with $urlRulesPrefix).
277
     * @since 1.0.0
278
     */
279
    public $authorizePath = 'authorize';
280
281
    /**
282
     * @var string URL path for the access token endpoint (will be prefixed with $urlRulesPrefix).
283
     * @since 1.0.0
284
     */
285
    public $accessTokenPath = 'access-token';
286
287
    /**
288
     * @var string URL path for the certificates jwks endpoint (will be prefixed with $urlRulesPrefix).
289
     * @since 1.0.0
290
     */
291
    public $jwksPath = 'certs';
292
293
    /**
294
     * The URL to the page where the user can perform the client/scope authorization
295
     * (if `null` the build in page will be used).
296
     * @return string
297
     * @since 1.0.0
298
     */
299
    public $clientAuthorizationUrl = null;
300
301
    /**
302
     * @var string The URL path to the build in page where the user can authorize the client for the requested scopes
303
     * (will be prefixed with $urlRulesPrefix).
304
     * Note: This setting will only be used if $clientAuthorizationUrl is `null`.
305
     * @since 1.0.0
306
     */
307
    public $clientAuthorizationPath = 'authorize-client';
308
309
    /**
310
     * @var string The view to use in the "client authorization action" for the page where the user can
311
     * authorize the client for the requested scopes.
312
     * Note: This setting will only be used if $clientAuthorizationUrl is `null`.
313
     * @since 1.0.0
314
     */
315
    public $clientAuthorizationView = 'authorize-client';
316
317
    /**
318
     * @var string|null The URL path to the OpenID Connect Provider Configuration Information Action.
319
     * If set to `null` the endpoint will be disabled.
320
     * Note: This path is defined in the
321
     *       [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.4)
322
     *       specification and should normally not be changed.
323
     * @since 1.0.0
324
     */
325
    public $openIdConnectProviderConfigurationInformationPath = '.well-known/openid-configuration';
326
327
    /**
328
     * @var string The URL path to the OpenID Connect Userinfo Action (will be prefixed with $urlRulesPrefix).
329
     * Note: This setting will only be used if $enableOpenIdConnect and $openIdConnectUserinfoEndpoint are `true`.
330
     * @since 1.0.0
331
     */
332
    public $openIdConnectUserinfoPath = 'oidc/userinfo';
333
334
    /**
335
     * @var Oauth2GrantTypeFactoryInterface[]|GrantTypeInterface[]|string[]|Oauth2GrantTypeFactoryInterface|GrantTypeInterface|string|callable
336
     * The Oauth 2.0 Grant Types that the module will serve.
337
     * @since 1.0.0
338
     */
339
    public $grantTypes = [];
340
341
    /**
342
     * @var string|null Default Time To Live for the access token, used when the Grant Type does not specify it.
343
     * When `null` default value of 1 hour is used.
344
     * The format should be a DateInterval duration (https://www.php.net/manual/en/dateinterval.construct.php).
345
     * @since 1.0.0
346
     */
347
    public $defaultAccessTokenTTL = null;
348
349
    /**
350
     * @var bool Should the resource server check for revocation of the access token.
351
     * @since 1.0.0
352
     */
353
    public $resourceServerAccessTokenRevocationValidation = true;
354
355
    /**
356
     * @var bool Enable support for OpenIdvConnect.
357
     * @since 1.0.0
358
     */
359
    public $enableOpenIdConnect = false;
360
361
    /**
362
     * @var bool Enable the .well-known/openid-configuration discovery endpoint.
363
     * @since 1.0.0
364
     */
365
    public $enableOpenIdConnectDiscovery = true;
366
367
    /**
368
     * @var bool include `grant_types_supported` in the OpenIdConnect Discovery.
369
     * Note: Since grant types can be specified per client not all clients might support all enabled grant types.
370
     * @since 1.0.0
371
     */
372
    public $openIdConnectDiscoveryIncludeSupportedGrantTypes = true;
373
374
    /**
375
     * @var string URL to include in the OpenID Connect Discovery Service of a page containing
376
     * human-readable information that developers might want or need to know when using the OpenID Provider.
377
     * @see 'service_documentation' in https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.3
378
     * @since 1.0.0
379
     */
380
    public $openIdConnectDiscoveryServiceDocumentationUrl = null;
381
382
    /**
383
     * @var string|bool A string to a custom userinfo endpoint or `true` to enable the build in endpoint.
384
     * @since 1.0.0
385
     */
386
    public $openIdConnectUserinfoEndpoint = true;
387
388
    /**
389
     * Warning! Enabling this setting might introduce privacy concerns since the client could poll for the
390
     * online status of a user.
391
     *
392
     * @var bool If this setting is disabled in case of OpenID Connect Context the Access Token won't include a
393
     * Refresh Token when the 'offline_access' scope is not included in the authorization request.
394
     * In some cases it might be needed to always include a Refresh Token, in that case enable this setting and
395
     * implement the `Oauth2OidcUserSessionStatusInterface` on the User Identity model.
396
     * @since 1.0.0
397
     */
398
    public $openIdConnectIssueRefreshTokenWithoutOfflineAccessScope = false;
399
400
    /**
401
     * @var int The default option for "User Account Selection' when not specified for a client.
402
     * @since 1.0.0
403
     */
404
    public $defaultUserAccountSelection = self::USER_ACCOUNT_SELECTION_DISABLED;
405
406
    /**
407
     * @var bool|null Display exception messages that might leak server details. This could be useful for debugging.
408
     * In case of `null` (default) the YII_DEBUG constant will be used.
409
     * Warning: Should NOT be enabled in production!
410
     * @since 1.0.0
411
     */
412
    public $displayConfidentialExceptionMessages = null;
413
414
    /**
415
     * @var string|null The namespace with which migrations will be created (and by which they will be located).
416
     * Note: The specified namespace must be defined as a Yii alias (e.g. '@app').
417
     * @since 1.0.0
418
     */
419
    public $migrationsNamespace = null;
420
    /**
421
     * @var string|null Optional prefix used in the name of generated migrations
422
     * @since 1.0.0
423
     */
424
    public $migrationsPrefix = null;
425
    /**
426
     * @var string|array|int|null Sets the file ownership of generated migrations
427
     * @see \yii\helpers\BaseFileHelper::changeOwnership()
428
     * @since 1.0.0
429
     */
430
    public $migrationsFileOwnership = null;
431
    /**
432
     * @var int|null Sets the file mode of generated migrations
433
     * @see \yii\helpers\BaseFileHelper::changeOwnership()
434
     * @since 1.0.0
435
     */
436
    public $migrationsFileMode = null;
437
438
    /**
439
     * @var Oauth2AuthorizationServerInterface|null Cache for the authorization server
440
     * @since 1.0.0
441
     */
442
    protected $_authorizationServer = null;
443
444
    /**
445
     * @var Oauth2ResourceServerInterface|null Cache for the resource server
446
     * @since 1.0.0
447
     */
448
    protected $_resourceServer = null;
449
450
    /**
451
     * @var Oauth2EncryptorInterface|null Cache for the Oauth2Encryptor
452
     * @since 1.0.0
453
     */
454
    protected $_encryptor = null;
455
456
    /**
457
     * @var string|null The authorization header used when the authorization request was validated.
458
     * @since 1.0.0
459
     */
460
    protected $_oauthClaimsAuthorizationHeader = null;
461
462
    /**
463
     * @inheritDoc
464
     * @throws InvalidConfigException
465
     */
466 128
    public function init()
467
    {
468 128
        parent::init();
469
470 128
        $app = Yii::$app;
471
472 128
        if ($app instanceof WebApplication || $this->appType == static::APPLICATION_TYPE_WEB) {
473 21
            $controllerMap = static::CONTROLLER_MAP[static::APPLICATION_TYPE_WEB];
474 128
        } elseif ($app instanceof ConsoleApplication || $this->appType == static::APPLICATION_TYPE_CONSOLE) {
475 128
            $controllerMap = static::CONTROLLER_MAP[static::APPLICATION_TYPE_CONSOLE];
476
        } else {
477 1
            throw new InvalidConfigException(
478 1
                'Unable to detect application type, configure it manually by setting `$appType`.'
479 1
            );
480
        }
481 128
        $controllerMap = array_filter(
482 128
            $controllerMap,
483 128
            fn($controllerSettings) => $controllerSettings['serverRole'] & $this->serverRole
484 128
        );
485 128
        $this->controllerMap = ArrayHelper::getColumn($controllerMap, 'controller');
486
487 128
        if (empty($this->identityClass)) {
488 1
            throw new InvalidConfigException('$identityClass must be set.');
489 128
        } elseif (!is_a($this->identityClass, Oauth2UserInterface::class, true)) {
490 1
            throw new InvalidConfigException(
491 1
                $this->identityClass . ' must implement ' . Oauth2UserInterface::class
492 1
            );
493
        }
494
495 128
        foreach (static::DEFAULT_INTERFACE_IMPLEMENTATIONS as $interface => $implementation) {
496 128
            if (!Yii::$container->has($interface)) {
497 128
                Yii::$container->set($interface, $implementation);
498
            }
499
        }
500
501 128
        if (empty($this->urlRulesPrefix)) {
502 128
            $this->urlRulesPrefix = $this->uniqueId;
503
        }
504
505 128
        $this->registerTranslations();
506
    }
507
508
    /**
509
     * @inheritdoc
510
     * @throws InvalidConfigException
511
     */
512 128
    public function bootstrap($app)
513
    {
514
        if (
515 128
            $app instanceof WebApplication
516 128
            && $this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER
517
        ) {
518 21
            $rules = [
519 21
                $this->accessTokenPath => Oauth2ServerControllerInterface::CONTROLLER_NAME
520 21
                    . '/' . Oauth2ServerControllerInterface::ACTION_NAME_ACCESS_TOKEN,
521 21
                $this->authorizePath => Oauth2ServerControllerInterface::CONTROLLER_NAME
522 21
                    . '/' . Oauth2ServerControllerInterface::ACTION_NAME_AUTHORIZE,
523 21
                $this->jwksPath => Oauth2CertificatesControllerInterface::CONTROLLER_NAME
524 21
                    . '/' . Oauth2CertificatesControllerInterface::ACTION_NAME_JWKS,
525 21
            ];
526
527 21
            if (empty($this->clientAuthorizationUrl)) {
528 20
                $rules[$this->clientAuthorizationPath] = Oauth2ConsentControllerInterface::CONTROLLER_NAME
529 20
                    . '/' . Oauth2ConsentControllerInterface::ACTION_NAME_AUTHORIZE_CLIENT;
530
            }
531
532 21
            if ($this->enableOpenIdConnect && $this->openIdConnectUserinfoEndpoint === true) {
533 21
                $rules[$this->openIdConnectUserinfoPath] =
534 21
                    Oauth2OidcControllerInterface::CONTROLLER_NAME
535 21
                    . '/' . Oauth2OidcControllerInterface::ACTION_NAME_USERINFO;
536
            }
537
538 21
            $urlManager = $app->getUrlManager();
539 21
            $urlManager->addRules([
540 21
                Yii::createObject([
541 21
                    'class' => GroupUrlRule::class,
542 21
                    'prefix' => $this->urlRulesPrefix,
543 21
                    'routePrefix' => $this->id,
544 21
                    'rules' => $rules,
545 21
                ]),
546 21
            ]);
547
548
            if (
549 21
                $this->enableOpenIdConnect
550 21
                && $this->enableOpenIdConnectDiscovery
551 21
                && $this->openIdConnectProviderConfigurationInformationPath
552
            ) {
553 21
                $urlManager->addRules([
554 21
                    Yii::createObject([
555 21
                        'class' => UrlRule::class,
556 21
                        'pattern' => $this->openIdConnectProviderConfigurationInformationPath,
557 21
                        'route' => $this->id
558 21
                            . '/' . Oauth2WellKnownControllerInterface::CONTROLLER_NAME
559 21
                            . '/' . Oauth2WellKnownControllerInterface::ACTION_NAME_OPENID_CONFIGURATION,
560 21
                    ]),
561 21
                ]);
562
            }
563
        }
564
    }
565
566
    /**
567
     * Registers the translations for the module
568
     * @param bool $force Force the setting of the translations (even if they are already defined).
569
     * @since 1.0.0
570
     */
571 128
    public function registerTranslations($force = false)
572
    {
573 128
        if ($force || !array_key_exists('oauth2', Yii::$app->i18n->translations)) {
574 128
            Yii::$app->i18n->translations['oauth2'] = [
575 128
                'class' => PhpMessageSource::class,
576 128
                'sourceLanguage' => 'en-US',
577 128
                'basePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
578 128
                'fileMap' => [
579 128
                    'oauth2' => 'oauth2.php',
580 128
                ],
581 128
            ];
582
        }
583
    }
584
585
    /**
586
     * @param string $identifier The client identifier
587
     * @param string $name The (user-friendly) name of the client
588
     * @param int $grantTypes The grant types enabled for this client.
589
     *        Use bitwise `OR` to combine multiple types,
590
     *        e.g. `Oauth2Module::GRANT_TYPE_AUTH_CODE | Oauth2Module::GRANT_TYPE_REFRESH_TOKEN`
591
     * @param string|string[] $redirectURIs One or multiple redirect URIs for the client
592
     * @param int $type The client type (e.g. Confidential or Public)
593
     *        See `\rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface::TYPES` for possible values
594
     * @param string|null $secret The client secret in case the client `type` is `confidential`.
595
     * @param string|string[]|array[]|Oauth2ScopeInterface[]|null $scopes
596
     * @param int|null $userId
597
     * @return Oauth2ClientInterface
598
     * @throws InvalidConfigException
599
     * @throws \yii\db\Exception
600
     */
601 12
    public function createClient(
602
        $identifier,
603
        $name,
604
        $grantTypes,
605
        $redirectURIs,
606
        $type,
607
        $secret = null,
608
        $scopes = null,
609
        $userId = null,
610
        $endUsersMayAuthorizeClient = null,
611
        $skipAuthorizationIfScopeIsAllowed = null
612
    ) {
613 12
        if (!($this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER)) {
614 1
            throw new InvalidCallException('Oauth2 server role does not include authorization server.');
615
        }
616
617
        /** @var Oauth2ClientInterface $client */
618 11
        $client = Yii::createObject([
619 11
            'class' => Oauth2ClientInterface::class,
620 11
            'identifier' => $identifier,
621 11
            'type' => $type,
622 11
            'name' => $name,
623 11
            'redirectUri' => $redirectURIs,
624 11
            'grantTypes' => $grantTypes,
625 11
            'endUsersMayAuthorizeClient' => $endUsersMayAuthorizeClient,
626 11
            'skip_authorization_if_scope_is_allowed' => $skipAuthorizationIfScopeIsAllowed,
627 11
            'clientCredentialsGrantUserId' => $userId
628 11
        ]);
629
630 11
        $transaction = $client::getDb()->beginTransaction();
631
632
        try {
633 11
            if ($type == Oauth2ClientInterface::TYPE_CONFIDENTIAL) {
634 11
                $client->setSecret($secret, $this->getEncryptor());
635
            }
636
637 10
            $client->persist();
638
639 10
            if (!empty($scopes)) {
640 8
                if (is_string($scopes)) {
641 2
                    $scopes = explode(' ', $scopes);
642 6
                } elseif (!is_array($scopes)) {
0 ignored issues
show
introduced by
The condition is_array($scopes) is always true.
Loading history...
643 1
                    throw new InvalidArgumentException('$scopes must be a string or an array.');
644
                }
645
646 7
                foreach ($scopes as $key => $value) {
647
648 7
                    $scopeIdentifier = null;
649 7
                    $clientScopeConfig = [
650 7
                        'class' => Oauth2ClientScopeInterface::class,
651 7
                        'client_id' => $client->getPrimaryKey(),
652 7
                    ];
653
654 7
                    if (is_string($value)) {
655 3
                        $scopeIdentifier = $value;
656 4
                    } elseif ($value instanceof Oauth2ScopeInterface) {
657 2
                        $scopePk = $value->getPrimaryKey();
658 2
                        if ($scopePk) {
659 1
                            $clientScopeConfig = ArrayHelper::merge(
660 1
                                $clientScopeConfig,
661 1
                                ['scope_id' => $scopePk]
662 1
                            );
663
                        } else {
664 2
                            $scopeIdentifier = $value->getIdentifier();
665
                        }
666 2
                    } elseif(is_array($value)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after ELSEIF keyword; 0 found
Loading history...
667 1
                        $clientScopeConfig = ArrayHelper::merge(
668 1
                            $clientScopeConfig,
669 1
                            $value,
670 1
                        );
671 1
                        if (empty($clientScopeConfig['scope_id'])) {
672 1
                            $scopeIdentifier = $key;
673
                        }
674
                    } else {
675 1
                        throw new InvalidArgumentException(
676 1
                            'If $scopes is an array, its values must be a string, array or an instance of '
677 1
                            . Oauth2ScopeInterface::class. '.'
0 ignored issues
show
Coding Style introduced by
Expected at least 1 space before "."; 0 found
Loading history...
678 1
                        );
679
                    }
680
681 6
                    if (isset($scopeIdentifier)) {
682 5
                        $scope = $this->getScopeRepository()->findModelByIdentifier($scopeIdentifier);
683 5
                        if (empty($scope)) {
684 1
                            throw new InvalidArgumentException('No scope with identifier "'
685 1
                                . $scopeIdentifier . '" found.');
686
                        }
687 4
                        $clientScopeConfig['scope_id'] = $scope->getPrimaryKey();
688
                    } else {
689 2
                        if (empty($clientScopeConfig['scope_id'])) {
690 1
                            throw new InvalidArgumentException('Element ' . $key . ' in $scope should specify either the scope id or its identifier.');
691
                        }
692
                    }
693
694
                    /** @var Oauth2ClientScopeInterface $clientScope */
695 4
                    $clientScope = Yii::createObject($clientScopeConfig);
696 4
                    $clientScope->persist();
697
                }
698
            }
699
700 6
            $transaction->commit();
701 5
        } catch (\Exception $e) {
702 5
            $transaction->rollBack();
703 5
            throw $e;
704
        }
705
706 6
        return $client;
707
    }
708
709
    /**
710
     * @return CryptKey The private key of the server.
711
     * @throws InvalidConfigException
712
     * @since 1.0.0
713
     */
714 21
    public function getPrivateKey()
715
    {
716 21
        $privateKey = $this->privateKey;
717 21
        if (StringHelper::startsWith($privateKey, '@')) {
718 18
            $privateKey = 'file://' . Yii::getAlias($privateKey);
0 ignored issues
show
Bug introduced by
Are you sure Yii::getAlias($privateKey) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

718
            $privateKey = 'file://' . /** @scrutinizer ignore-type */ Yii::getAlias($privateKey);
Loading history...
719
        }
720 21
        return Yii::createObject(CryptKey::class, [$privateKey, $this->privateKeyPassphrase]);
721
    }
722
723
    /**
724
     * @return CryptKey The public key of the server.
725
     * @throws InvalidConfigException
726
     * @since 1.0.0
727
     */
728 9
    public function getPublicKey()
729
    {
730 9
        $publicKey = $this->publicKey;
731 9
        if (StringHelper::startsWith($publicKey, '@')) {
732 6
            $publicKey = 'file://' . Yii::getAlias($publicKey);
0 ignored issues
show
Bug introduced by
Are you sure Yii::getAlias($publicKey) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

732
            $publicKey = 'file://' . /** @scrutinizer ignore-type */ Yii::getAlias($publicKey);
Loading history...
733
        }
734 9
        return Yii::createObject(CryptKey::class, [$publicKey]);
735
    }
736
737
    /**
738
     * @return Oauth2AuthorizationServerInterface The authorization server.
739
     * @throws InvalidConfigException
740
     * @since 1.0.0
741
     */
742 26
    public function getAuthorizationServer()
743
    {
744 26
        if (!($this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER)) {
745 1
            throw new InvalidCallException('Oauth2 server role does not include authorization server.');
746
        }
747
748 25
        if (!$this->_authorizationServer) {
749 25
            $this->ensureProperties(static::REQUIRED_SETTINGS_AUTHORIZATION_SERVER);
750
751 20
            if (!$this->getEncryptor()->hasKey($this->defaultStorageEncryptionKey)) {
752 1
                throw new InvalidConfigException(
753 1
                    'Key "' . $this->defaultStorageEncryptionKey . '" is not set in $storageEncryptionKeys'
754 1
                );
755
            }
756
757
            /** @var Oauth2EncryptionKeyFactoryInterface $keyFactory */
758 18
            $keyFactory = Yii::createObject(Oauth2EncryptionKeyFactoryInterface::class);
759
            try {
760 18
                $codesEncryptionKey = $keyFactory->createFromAsciiSafeString($this->codesEncryptionKey);
761 1
            } catch (BadFormatException $e) {
762 1
                throw new InvalidConfigException(
763 1
                    '$codesEncryptionKey is malformed: ' . $e->getMessage(),
764 1
                    0,
765 1
                    $e
766 1
                );
767
            } catch (EnvironmentIsBrokenException $e) {
768
                throw new InvalidConfigException(
769
                    'Could not instantiate $codesEncryptionKey: ' . $e->getMessage(),
770
                    0,
771
                    $e
772
                );
773
            }
774
775 17
            $responseType = null;
776 17
            if ($this->enableOpenIdConnect) {
777 17
                $responseType = Yii::createObject(Oauth2OidcBearerTokenResponseInterface::class, [
778 17
                    $this,
779 17
                ]);
780
            }
781
782 17
            $this->_authorizationServer = Yii::createObject(Oauth2AuthorizationServerInterface::class, [
783 17
                $this->getClientRepository(),
784 17
                $this->getAccessTokenRepository(),
785 17
                $this->getScopeRepository(),
786 17
                $this->getPrivateKey(),
787 17
                $codesEncryptionKey,
788 17
                $responseType
789 17
            ]);
790
791 17
            if (!empty($this->grantTypes)) {
792 17
                $grantTypes = $this->grantTypes;
793
794 17
                if (is_callable($grantTypes)) {
795 1
                    call_user_func($grantTypes, $this->_authorizationServer, $this);
0 ignored issues
show
Bug introduced by
It seems like $grantTypes can also be of type League\OAuth2\Server\Grant\GrantTypeInterface and rhertogh\Yii2Oauth2Serve...antTypeFactoryInterface; however, parameter $callback of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

795
                    call_user_func(/** @scrutinizer ignore-type */ $grantTypes, $this->_authorizationServer, $this);
Loading history...
796
                } else {
797 16
                    if (!is_array($grantTypes)) {
798 2
                        $grantTypes = [$grantTypes];
799
                    }
800
801 16
                    foreach ($grantTypes as $grantTypeDefinition) {
802 16
                        if ($grantTypeDefinition instanceof GrantTypeInterface) {
803 1
                            $accessTokenTTL = $this->defaultAccessTokenTTL
804
                                ? new \DateInterval($this->defaultAccessTokenTTL)
805 1
                                : null;
806 1
                            $this->_authorizationServer->enableGrantType($grantTypeDefinition, $accessTokenTTL);
807
                        } elseif (
808
                            (
809 15
                                is_numeric($grantTypeDefinition)
810 15
                                && array_key_exists($grantTypeDefinition, static::DEFAULT_GRANT_TYPE_FACTORIES)
811
                            )
812 15
                            || is_a($grantTypeDefinition, Oauth2GrantTypeFactoryInterface::class, true)
813
                        ) {
814
                            if (
815 14
                                is_numeric($grantTypeDefinition)
816 14
                                && array_key_exists($grantTypeDefinition, static::DEFAULT_GRANT_TYPE_FACTORIES)
817
                            ) {
818 14
                                $grantTypeDefinition = static::DEFAULT_GRANT_TYPE_FACTORIES[$grantTypeDefinition];
819
                            }
820
821
                            /** @var Oauth2GrantTypeFactoryInterface $factory */
822 14
                            $factory = Yii::createObject([
823 14
                                'class' => $grantTypeDefinition,
824 14
                                'module' => $this,
825 14
                            ]);
826 14
                            $accessTokenTTL = $factory->accessTokenTTL ?? $this->defaultAccessTokenTTL ?? null;
0 ignored issues
show
Bug introduced by
Accessing accessTokenTTL on the interface rhertogh\Yii2Oauth2Serve...antTypeFactoryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
827 14
                            $this->_authorizationServer->enableGrantType(
828 14
                                $factory->getGrantType(),
829 14
                                $accessTokenTTL ? new \DateInterval($accessTokenTTL) : null
830 14
                            );
831
                        } else {
832 1
                            throw new InvalidConfigException(
833 1
                                'Unknown grantType '
834 1
                                . (
835 1
                                    is_scalar($grantTypeDefinition)
836 1
                                        ? '"' . $grantTypeDefinition . '".'
837 1
                                        : 'with data type ' . gettype($grantTypeDefinition)
838 1
                                )
839 1
                            );
840
                        }
841
                    }
842
                }
843
            }
844
        }
845
846 16
        return $this->_authorizationServer;
847
    }
848
849
    /**
850
     * @inheritDoc
851
     * @throws InvalidConfigException
852
     */
853 6
    public function getOidcScopeCollection()
854
    {
855 6
        if ($this->_oidcScopeCollection === null) {
856 6
            $openIdConnectScopes = $this->getOpenIdConnectScopes();
857 6
            if ($openIdConnectScopes instanceof Oauth2OidcScopeCollectionInterface) {
858 1
                $this->_oidcScopeCollection = $openIdConnectScopes;
859 5
            } elseif (is_callable($openIdConnectScopes)) {
860 1
                $this->_oidcScopeCollection = call_user_func($openIdConnectScopes, $this);
861 1
                if (!($this->_oidcScopeCollection instanceof Oauth2OidcScopeCollectionInterface)) {
862 1
                    throw new InvalidConfigException(
863 1
                        '$openIdConnectScopes must return an instance of '
864 1
                            . Oauth2OidcScopeCollectionInterface::class
865 1
                    );
866
                }
867 4
            } elseif (is_array($openIdConnectScopes) || is_string($openIdConnectScopes)) {
868 3
                $this->_oidcScopeCollection = Yii::createObject([
869 3
                    'class' => Oauth2OidcScopeCollectionInterface::class,
870 3
                    'oidcScopes' => (array)$openIdConnectScopes,
871 3
                ]);
872
            } else {
873 1
                throw new InvalidConfigException(
874 1
                    '$openIdConnectScopes must be a callable, array, string or '
875 1
                        . Oauth2OidcScopeCollectionInterface::class
876 1
                );
877
            }
878
        }
879
880 5
        return $this->_oidcScopeCollection;
881
    }
882
883
    /**
884
     * @return Oauth2ResourceServerInterface The resource server.
885
     * @throws InvalidConfigException
886
     * @since 1.0.0
887
     */
888 7
    public function getResourceServer()
889
    {
890 7
        if (!($this->serverRole & static::SERVER_ROLE_RESOURCE_SERVER)) {
891 1
            throw new InvalidCallException('Oauth2 server role does not include resource server.');
892
        }
893
894 6
        if (!$this->_resourceServer) {
895 6
            $this->ensureProperties(static::REQUIRED_SETTINGS_RESOURCE_SERVER);
896
897 5
            $accessTokenRepository = $this->getAccessTokenRepository()
898 5
                ->setRevocationValidation($this->resourceServerAccessTokenRevocationValidation);
899
900 5
            $this->_resourceServer = Yii::createObject(Oauth2ResourceServerInterface::class, [
901 5
                $accessTokenRepository,
902 5
                $this->getPublicKey(),
903 5
            ]);
904
        }
905
906 5
        return $this->_resourceServer;
907
    }
908
909
    /**
910
     * @return Oauth2EncryptorInterface The data encryptor for the module.
911
     * @throws InvalidConfigException
912
     * @since 1.0.0
913
     */
914 33
    public function getEncryptor()
915
    {
916 33
        if (!$this->_encryptor) {
917 33
            $this->_encryptor = Yii::createObject([
918 33
                'class' => Oauth2EncryptorInterface::class,
919 33
                'keys' => $this->storageEncryptionKeys,
920 33
                'defaultKeyName' => $this->defaultStorageEncryptionKey,
921 33
            ]);
922
        }
923
924 32
        return $this->_encryptor;
925
    }
926
927
    /**
928
     * @param string|null $newKeyName
929
     * @return array
930
     * @throws InvalidConfigException
931
     */
932 1
    public function rotateStorageEncryptionKeys($newKeyName = null)
933
    {
934 1
        $encryptor = $this->getEncryptor();
935
936 1
        $result = [];
937 1
        foreach (static::ENCRYPTED_MODELS as $modelInterface) {
938 1
            $modelClass = DiHelper::getValidatedClassName($modelInterface);
939 1
            if (!is_a($modelClass, Oauth2EncryptedStorageInterface::class, true)) {
940
                throw new InvalidConfigException($modelInterface . ' must implement '
941
                    . Oauth2EncryptedStorageInterface::class);
942
            }
943 1
            $result[$modelClass] = $modelClass::rotateStorageEncryptionKeys($encryptor, $newKeyName);
944
        }
945
946 1
        return $result;
947
    }
948
949
    /**
950
     * @return array
951
     * @throws InvalidConfigException
952
     */
953
    public function getStorageEncryptionKeyUsage()
954
    {
955
        $encryptor = $this->getEncryptor();
956
957
        $result = [];
958
        foreach (static::ENCRYPTED_MODELS as $modelInterface) {
959
            $modelClass = DiHelper::getValidatedClassName($modelInterface);
960
            if (!is_a($modelClass, Oauth2EncryptedStorageInterface::class, true)) {
961
                throw new InvalidConfigException($modelInterface . ' must implement '
962
                    . Oauth2EncryptedStorageInterface::class);
963
            }
964
965
            $result[$modelClass] = $modelClass::getUsedStorageEncryptionKeys($encryptor);
966
        }
967
968
        return $result;
969
    }
970
971
    /**
972
     * Generates a redirect Response to the client authorization page where the user is prompted to authorize the
973
     * client and requested scope.
974
     * @param Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest
975
     * @return Response
976
     * @since 1.0.0
977
     */
978 5
    public function generateClientAuthReqRedirectResponse($clientAuthorizationRequest)
979
    {
980 5
        $this->setClientAuthReqSession($clientAuthorizationRequest);
981 5
        if (!empty($this->clientAuthorizationUrl)) {
982 1
            $url = $this->clientAuthorizationUrl;
983
        } else {
984 4
            $url = $this->uniqueId
985 4
                . '/' . Oauth2ConsentControllerInterface::CONTROLLER_NAME
986 4
                . '/' . Oauth2ConsentControllerInterface::ACTION_NAME_AUTHORIZE_CLIENT;
987
        }
988 5
        return Yii::$app->response->redirect([
989 5
            $url,
990 5
            'clientAuthorizationRequestId' => $clientAuthorizationRequest->getRequestId(),
991 5
        ]);
992
    }
993
994
    /**
995
     * Get a previously stored Client Authorization Request from the session.
996
     * @param string $requestId
997
     * @return Oauth2ClientAuthorizationRequestInterface|null
998
     * @since 1.0.0
999
     */
1000 5
    public function getClientAuthReqSession($requestId)
1001
    {
1002 5
        if (empty($requestId)) {
1003
            return null;
1004
        }
1005 5
        $key = static::CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX . $requestId;
1006 5
        $clientAuthorizationRequest = Yii::$app->session->get($key);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1006
        /** @scrutinizer ignore-call */ 
1007
        $clientAuthorizationRequest = Yii::$app->session->get($key);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1007 5
        if (!($clientAuthorizationRequest instanceof Oauth2ClientAuthorizationRequestInterface)) {
1008 2
            if (!empty($clientAuthorizationRequest)) {
1009 1
                Yii::warning(
1010 1
                    'Found a ClientAuthorizationRequestSession with key "' . $key
1011 1
                        . '", but it\'s not a ' . Oauth2ClientAuthorizationRequestInterface::class
1012 1
                );
1013
            }
1014 2
            return null;
1015
        }
1016 5
        if ($clientAuthorizationRequest->getRequestId() !== $requestId) {
1017 1
            Yii::warning(
1018 1
                'Found a ClientAuthorizationRequestSession with key "' . $key
1019 1
                    . '", but its request id does not match "' . $requestId . '".'
1020 1
            );
1021 1
            return null;
1022
        }
1023 5
        $clientAuthorizationRequest->setModule($this);
1024
1025 5
        return $clientAuthorizationRequest;
1026
    }
1027
1028
    /**
1029
     * Stores the Client Authorization Request in the session.
1030
     * @param Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest
1031
     * @since 1.0.0
1032
     */
1033 8
    public function setClientAuthReqSession($clientAuthorizationRequest)
1034
    {
1035 8
        $requestId = $clientAuthorizationRequest->getRequestId();
1036 8
        if (empty($requestId)) {
1037 1
            throw new InvalidArgumentException('$scopeAuthorization must return a request id.');
1038
        }
1039 7
        $key = static::CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX . $requestId;
1040 7
        Yii::$app->session->set($key, $clientAuthorizationRequest);
1041
    }
1042
1043
    /**
1044
     * Stores whether the user was authenticated during the completion of the Client Authorization Request.
1045
     * @param string $clientAuthorizationRequestId
1046
     * @param bool $authenticatedDuringRequest
1047
     * @since 1.0.0
1048
     */
1049
    public function setUserAuthenticatedDuringClientAuthRequest(
1050
        $clientAuthorizationRequestId,
1051
        $authenticatedDuringRequest
1052
    ) {
1053
        $clientAuthorizationRequest = $this->getClientAuthReqSession($clientAuthorizationRequestId);
1054
        if ($clientAuthorizationRequest) {
1055
            $clientAuthorizationRequest->setUserAuthenticatedDuringRequest($authenticatedDuringRequest);
1056
            $this->setClientAuthReqSession($clientAuthorizationRequest);
1057
        }
1058
    }
1059
1060
    /**
1061
     * Stores the user identity selected during the completion of the Client Authorization Request.
1062
     * @param string $clientAuthorizationRequestId
1063
     * @param Oauth2UserInterface $userIdentity
1064
     * @since 1.0.0
1065
     */
1066
    public function setClientAuthRequestUserIdentity($clientAuthorizationRequestId, $userIdentity)
1067
    {
1068
        $clientAuthorizationRequest = $this->getClientAuthReqSession($clientAuthorizationRequestId);
1069
        if ($clientAuthorizationRequest) {
1070
            $clientAuthorizationRequest->setUserIdentity($userIdentity);
1071
            $this->setClientAuthReqSession($clientAuthorizationRequest);
1072
        }
1073
    }
1074
1075
    /**
1076
     * Clears a Client Authorization Request from the session storage.
1077
     * @param string $requestId
1078
     * @since 1.0.0
1079
     */
1080 2
    public function removeClientAuthReqSession($requestId)
1081
    {
1082 2
        if (empty($requestId)) {
1083 1
            throw new InvalidArgumentException('$requestId can not be empty.');
1084
        }
1085 1
        $key = static::CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX . $requestId;
1086 1
        Yii::$app->session->remove($key);
1087
    }
1088
1089
    /**
1090
     * Generates a redirect Response when the Client Authorization Request is completed.
1091
     * @param Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest
1092
     * @return Response
1093
     * @since 1.0.0
1094
     */
1095 1
    public function generateClientAuthReqCompledRedirectResponse($clientAuthorizationRequest)
1096
    {
1097 1
        $clientAuthorizationRequest->processAuthorization();
1098 1
        $this->setClientAuthReqSession($clientAuthorizationRequest);
1099 1
        return Yii::$app->response->redirect($clientAuthorizationRequest->getAuthorizationRequestUrl());
1100
    }
1101
1102
    /**
1103
     * @return IdentityInterface|Oauth2UserInterface|Oauth2OidcUserInterface|null
1104
     * @throws InvalidConfigException
1105
     * @since 1.0.0
1106
     */
1107 5
    public function getUserIdentity()
1108
    {
1109 5
        $user = Yii::$app->user->identity;
1110 5
        if (!empty($user) && !($user instanceof Oauth2UserInterface)) {
1111 1
            throw new InvalidConfigException(
1112 1
                'Yii::$app->user->identity (currently ' . get_class($user)
1113 1
                    . ') must implement ' . Oauth2UserInterface::class
1114 1
            );
1115
        }
1116 4
        return $user;
1117
    }
1118
1119
    /**
1120
     * Validates a bearer token authenticated request. Note: this method does not return a result but will throw
1121
     * an exception when the authentication fails.
1122
     * @throws InvalidConfigException
1123
     * @throws Oauth2ServerException
1124
     * @since 1.0.0
1125
     */
1126 3
    public function validateAuthenticatedRequest()
1127
    {
1128 3
        $psr7Request = Psr7Helper::yiiToPsr7Request(Yii::$app->request);
0 ignored issues
show
Bug introduced by
It seems like Yii::app->request can also be of type yii\console\Request; however, parameter $request of rhertogh\Yii2Oauth2Serve...per::yiiToPsr7Request() does only seem to accept yii\web\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1128
        $psr7Request = Psr7Helper::yiiToPsr7Request(/** @scrutinizer ignore-type */ Yii::$app->request);
Loading history...
1129
1130 3
        $psr7Request = $this->getResourceServer()->validateAuthenticatedRequest($psr7Request);
1131
1132 3
        $this->_oauthClaims = $psr7Request->getAttributes();
1133 3
        $this->_oauthClaimsAuthorizationHeader = Yii::$app->request->getHeaders()->get('Authorization');
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->request->getHe...)->get('Authorization') can also be of type array. However, the property $_oauthClaimsAuthorizationHeader is declared as type null|string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1134
    }
1135
1136
    /**
1137
     * Find a user identity bases on an access token.
1138
     * Note: validateAuthenticatedRequest() must be called before this method is called.
1139
     * @param string $token
1140
     * @param string $type
1141
     * @return Oauth2UserInterface|null
1142
     * @throws InvalidConfigException
1143
     * @throws Oauth2ServerException
1144
     * @see validateAuthenticatedRequest()
1145
     * @since 1.0.0
1146
     */
1147 4
    public function findIdentityByAccessToken($token, $type)
1148
    {
1149 4
        if (!is_a($type, Oauth2HttpBearerAuthInterface::class, true)) {
1150 1
            throw new InvalidCallException($type . ' must implement ' . Oauth2HttpBearerAuthInterface::class);
1151
        }
1152
1153
        if (
1154 3
            !preg_match('/^Bearer\s+(.*?)$/', $this->_oauthClaimsAuthorizationHeader, $matches)
0 ignored issues
show
Bug introduced by
It seems like $this->_oauthClaimsAuthorizationHeader can also be of type null; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1154
            !preg_match('/^Bearer\s+(.*?)$/', /** @scrutinizer ignore-type */ $this->_oauthClaimsAuthorizationHeader, $matches)
Loading history...
1155 3
            || !Yii::$app->security->compareString($matches[1], $token)
1156
        ) {
1157 1
            throw new InvalidCallException(
1158 1
                'validateAuthenticatedRequest() must be called before findIdentityByAccessToken().'
1159 1
            );
1160
        }
1161
1162 2
        $userId = $this->getRequestOauthUserId();
1163 2
        if (empty($userId)) {
1164 1
            return null;
1165
        }
1166
1167 1
        return $this->identityClass::findIdentity($userId);
1168
    }
1169
1170
    /**
1171
     * Generate a "Personal Access Token" (PAT) which can be used as an alternative to using passwords
1172
     * for authentication (e.g. when using an API or command line).
1173
     *
1174
     * Note: Personal Access Tokens are intended to access resources on behalf users themselves.
1175
     *       To grant access to resources on behalf of an organization, or for long-lived integrations,
1176
     *       you most likely want to define an Oauth2 Client with the "Client Credentials" grant
1177
     *       (https://oauth.net/2/grant-types/client-credentials).
1178
     *
1179
     * @param string $clientIdentifier The Oauth2 client identifier for which the PAT should be generated.
1180
     * @param int|string $userIdentifier The identifier (primary key) of the user for which the PAT should be generated.
1181
     * @param Oauth2ScopeInterface[]|string[]|string|null $scope The Access Token scope.
1182
     * @param string|true|null $clientSecret If the client is a "confidential" client the secret is required.
1183
     *        If the boolean value `true` is passed, the client secret is automatically injected.
1184
     * @return Oauth2AccessTokenData
1185
     */
1186 3
    public function generatePersonalAccessToken($clientIdentifier, $userIdentifier, $scope = null, $clientSecret = null)
1187
    {
1188 3
        if (is_array($scope)) {
1189 2
            $scopeIdentifiers = [];
1190 2
            foreach ($scope as $scopeItem) {
1191 2
                if (is_string($scopeItem)) {
1192 1
                    $scopeIdentifiers[] = $scopeItem;
1193 1
                } elseif ($scopeItem instanceof Oauth2ScopeInterface) {
1194 1
                    $scopeIdentifiers[] = $scopeItem->getIdentifier();
1195
                } else {
1196
                    throw new InvalidArgumentException('If $scope is an array its elements must be either'
1197
                        . ' a string or an instance of ' . Oauth2ScopeInterface::class);
1198
                }
1199
            }
1200 2
            $scope = implode(' ', $scopeIdentifiers);
1201
        }
1202
1203 3
        if ($clientSecret === true) {
1204
            /** @var Oauth2ClientInterface $client */
1205 3
            $client = $this->getClientRepository()->findModelByIdentifier($clientIdentifier);
1206 3
            if ($client && $client->isConfidential()) {
1207 3
                $clientSecret = $client->getDecryptedSecret($this->getEncryptor());
1208
            } else {
1209
                $clientSecret = null;
1210
            }
1211
        }
1212
1213 3
        $request = (new Psr7ServerRequest('POST', ''))->withParsedBody([
1214 3
            'grant_type' => static::GRANT_TYPE_IDENTIFIER_PERSONAL_ACCESS_TOKEN,
1215 3
            'client_id' => $clientIdentifier,
1216 3
            'client_secret' => $clientSecret,
1217 3
            'user_id' => $userIdentifier,
1218 3
            'scope' => $scope,
1219 3
        ]);
1220
1221 3
        return new Oauth2AccessTokenData(Json::decode(
0 ignored issues
show
Bug introduced by
It seems like yii\helpers\Json::decode...etBody()->__toString()) can also be of type null; however, parameter $data of rhertogh\Yii2Oauth2Serve...okenData::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1221
        return new Oauth2AccessTokenData(/** @scrutinizer ignore-type */ Json::decode(
Loading history...
1222 3
            $this->getAuthorizationServer()
1223 3
                ->respondToAccessTokenRequest(
1224 3
                    $request,
1225 3
                    new Psr7Response()
1226 3
                )
1227 3
                ->getBody()
1228 3
                ->__toString()
1229 3
        ));
1230
    }
1231
1232
    /**
1233
     * @inheritDoc
1234
     */
1235 5
    protected function getRequestOauthClaim($attribute, $default = null)
1236
    {
1237 5
        if (empty($this->_oauthClaimsAuthorizationHeader)) {
1238
            // User authorization was not processed by Oauth2Module.
1239 1
            return $default;
1240
        }
1241 4
        if (Yii::$app->request->getHeaders()->get('Authorization') !== $this->_oauthClaimsAuthorizationHeader) {
1242 1
            throw new InvalidCallException(
1243 1
                'App Request Authorization header does not match the processed Oauth header.'
1244 1
            );
1245
        }
1246 3
        return $this->_oauthClaims[$attribute] ?? $default;
1247
    }
1248
1249
    /**
1250
     * Helper function to ensure the required properties are configured for the module.
1251
     * @param string[] $properties
1252
     * @throws InvalidConfigException
1253
     * @since 1.0.0
1254
     */
1255 31
    protected function ensureProperties($properties)
1256
    {
1257 31
        foreach ($properties as $property) {
1258 31
            if (empty($this->$property)) {
1259 6
                throw new InvalidConfigException( __CLASS__ . '::$' . $property . ' must be set.');
1260
            }
1261
        }
1262
    }
1263
}
1264