Passed
Push — master ( 19d158...b4bcbe )
by Rutger
02:56
created

Oauth2Module::getResourceServer()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 19
ccs 12
cts 12
cp 1
rs 9.9332
cc 3
nc 3
nop 0
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 The URL path to the OpenID Connect Userinfo Action (will be prefixed with $urlRulesPrefix).
319
     * Note: This setting will only be used if $enableOpenIdConnect and $openIdConnectUserinfoEndpoint are `true`.
320
     * @since 1.0.0
321
     */
322
    public $openIdConnectUserinfoPath = 'oidc/userinfo';
323
324
    /**
325
     * @var Oauth2GrantTypeFactoryInterface[]|GrantTypeInterface[]|string[]|Oauth2GrantTypeFactoryInterface|GrantTypeInterface|string|callable
326
     * The Oauth 2.0 Grant Types that the module will serve.
327
     * @since 1.0.0
328
     */
329
    public $grantTypes = [];
330
331
    /**
332
     * @var string|null Default Time To Live for the access token, used when the Grant Type does not specify it.
333
     * When `null` default value of 1 hour is used.
334
     * The format should be a DateInterval duration (https://www.php.net/manual/en/dateinterval.construct.php).
335
     * @since 1.0.0
336
     */
337
    public $defaultAccessTokenTTL = null;
338
339
    /**
340
     * @var bool Should the resource server check for revocation of the access token.
341
     * @since 1.0.0
342
     */
343
    public $resourceServerAccessTokenRevocationValidation = true;
344
345
    /**
346
     * @var bool Enable support for OpenIdvConnect.
347
     * @since 1.0.0
348
     */
349
    public $enableOpenIdConnect = false;
350
351
    /**
352
     * @var bool Enable the .well-known/openid-configuration discovery endpoint.
353
     * @since 1.0.0
354
     */
355
    public $enableOpenIdConnectDiscovery = true;
356
357
    /**
358
     * @var bool include `grant_types_supported` in the OpenIdConnect Discovery.
359
     * Note: Since grant types can be specified per client not all clients might support all enabled grant types.
360
     * @since 1.0.0
361
     */
362
    public $openIdConnectDiscoveryIncludeSupportedGrantTypes = true;
363
364
    /**
365
     * @var string URL to include in the OpenID Connect Discovery Service of a page containing
366
     * human-readable information that developers might want or need to know when using the OpenID Provider.
367
     * @see 'service_documentation' in https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.3
368
     * @since 1.0.0
369
     */
370
    public $openIdConnectDiscoveryServiceDocumentationUrl = null;
371
372
    /**
373
     * @var string|bool A string to a custom userinfo endpoint or `true` to enable the build in endpoint.
374
     * @since 1.0.0
375
     */
376
    public $openIdConnectUserinfoEndpoint = true;
377
378
    /**
379
     * Warning! Enabling this setting might introduce privacy concerns since the client could poll for the
380
     * online status of a user.
381
     *
382
     * @var bool If this setting is disabled in case of OpenID Connect Context the Access Token won't include a
383
     * Refresh Token when the 'offline_access' scope is not included in the authorization request.
384
     * In some cases it might be needed to always include a Refresh Token, in that case enable this setting and
385
     * implement the `Oauth2OidcUserSessionStatusInterface` on the User Identity model.
386
     * @since 1.0.0
387
     */
388
    public $openIdConnectIssueRefreshTokenWithoutOfflineAccessScope = false;
389
390
    /**
391
     * @var int The default option for "User Account Selection' when not specified for a client.
392
     * @since 1.0.0
393
     */
394
    public $defaultUserAccountSelection = self::USER_ACCOUNT_SELECTION_DISABLED;
395
396
    /**
397
     * @var bool|null Display exception messages that might leak server details. This could be useful for debugging.
398
     * In case of `null` (default) the YII_DEBUG constant will be used.
399
     * Warning: Should NOT be enabled in production!
400
     * @since 1.0.0
401
     */
402
    public $displayConfidentialExceptionMessages = null;
403
404
    /**
405
     * @var string|null The namespace with which migrations will be created (and by which they will be located).
406
     * Note: The specified namespace must be defined as a Yii alias (e.g. '@app').
407
     * @since 1.0.0
408
     */
409
    public $migrationsNamespace = null;
410
    /**
411
     * @var string|null Optional prefix used in the name of generated migrations
412
     * @since 1.0.0
413
     */
414
    public $migrationsPrefix = null;
415
    /**
416
     * @var string|array|int|null Sets the file ownership of generated migrations
417
     * @see \yii\helpers\BaseFileHelper::changeOwnership()
418
     * @since 1.0.0
419
     */
420
    public $migrationsFileOwnership = null;
421
    /**
422
     * @var int|null Sets the file mode of generated migrations
423
     * @see \yii\helpers\BaseFileHelper::changeOwnership()
424
     * @since 1.0.0
425
     */
426
    public $migrationsFileMode = null;
427
428
    /**
429
     * @var Oauth2AuthorizationServerInterface|null Cache for the authorization server
430
     * @since 1.0.0
431
     */
432
    protected $_authorizationServer = null;
433
434
    /**
435
     * @var Oauth2ResourceServerInterface|null Cache for the resource server
436
     * @since 1.0.0
437
     */
438
    protected $_resourceServer = null;
439
440
    /**
441
     * @var Oauth2EncryptorInterface|null Cache for the Oauth2Encryptor
442
     * @since 1.0.0
443
     */
444
    protected $_encryptor = null;
445
446
    /**
447
     * @var string|null The authorization header used when the authorization request was validated.
448
     * @since 1.0.0
449
     */
450
    protected $_oauthClaimsAuthorizationHeader = null;
451
452
    /**
453
     * @inheritDoc
454
     * @throws InvalidConfigException
455
     */
456 128
    public function init()
457
    {
458 128
        parent::init();
459
460 128
        $app = Yii::$app;
461
462 128
        if ($app instanceof WebApplication || $this->appType == static::APPLICATION_TYPE_WEB) {
463 21
            $controllerMap = static::CONTROLLER_MAP[static::APPLICATION_TYPE_WEB];
464 128
        } elseif ($app instanceof ConsoleApplication || $this->appType == static::APPLICATION_TYPE_CONSOLE) {
465 128
            $controllerMap = static::CONTROLLER_MAP[static::APPLICATION_TYPE_CONSOLE];
466
        } else {
467 1
            throw new InvalidConfigException(
468 1
                'Unable to detect application type, configure it manually by setting `$appType`.'
469 1
            );
470
        }
471 128
        $controllerMap = array_filter(
472 128
            $controllerMap,
473 128
            fn($controllerSettings) => $controllerSettings['serverRole'] & $this->serverRole
474 128
        );
475 128
        $this->controllerMap = ArrayHelper::getColumn($controllerMap, 'controller');
476
477 128
        if (empty($this->identityClass)) {
478 1
            throw new InvalidConfigException('$identityClass must be set.');
479 128
        } elseif (!is_a($this->identityClass, Oauth2UserInterface::class, true)) {
480 1
            throw new InvalidConfigException(
481 1
                $this->identityClass . ' must implement ' . Oauth2UserInterface::class
482 1
            );
483
        }
484
485 128
        foreach (static::DEFAULT_INTERFACE_IMPLEMENTATIONS as $interface => $implementation) {
486 128
            if (!Yii::$container->has($interface)) {
487 128
                Yii::$container->set($interface, $implementation);
488
            }
489
        }
490
491 128
        if (empty($this->urlRulesPrefix)) {
492 128
            $this->urlRulesPrefix = $this->uniqueId;
493
        }
494
495 128
        $this->registerTranslations();
496
    }
497
498
    /**
499
     * @inheritdoc
500
     * @throws InvalidConfigException
501
     */
502 128
    public function bootstrap($app)
503
    {
504
        if (
505 128
            $app instanceof WebApplication
506 128
            && $this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER
507
        ) {
508 21
            $rules = [
509 21
                $this->accessTokenPath => Oauth2ServerControllerInterface::CONTROLLER_NAME
510 21
                    . '/' . Oauth2ServerControllerInterface::ACTION_NAME_ACCESS_TOKEN,
511 21
                $this->authorizePath => Oauth2ServerControllerInterface::CONTROLLER_NAME
512 21
                    . '/' . Oauth2ServerControllerInterface::ACTION_NAME_AUTHORIZE,
513 21
                $this->jwksPath => Oauth2CertificatesControllerInterface::CONTROLLER_NAME
514 21
                    . '/' . Oauth2CertificatesControllerInterface::ACTION_NAME_JWKS,
515 21
            ];
516
517 21
            if (empty($this->clientAuthorizationUrl)) {
518 20
                $rules[$this->clientAuthorizationPath] = Oauth2ConsentControllerInterface::CONTROLLER_NAME
519 20
                    . '/' . Oauth2ConsentControllerInterface::ACTION_NAME_AUTHORIZE_CLIENT;
520
            }
521
522 21
            if ($this->enableOpenIdConnect && $this->openIdConnectUserinfoEndpoint === true) {
523 21
                $rules[$this->openIdConnectUserinfoPath] =
524 21
                    Oauth2OidcControllerInterface::CONTROLLER_NAME
525 21
                    . '/' . Oauth2OidcControllerInterface::ACTION_NAME_USERINFO;
526
            }
527
528 21
            $urlManager = $app->getUrlManager();
529 21
            $urlManager->addRules([
530 21
                Yii::createObject([
531 21
                    'class' => GroupUrlRule::class,
532 21
                    'prefix' => $this->urlRulesPrefix,
533 21
                    'routePrefix' => $this->id,
534 21
                    'rules' => $rules,
535 21
                ]),
536 21
            ]);
537
538 21
            if ($this->enableOpenIdConnect && $this->enableOpenIdConnectDiscovery) {
539 21
                $urlManager->addRules([
540 21
                    Yii::createObject([
541 21
                        'class' => UrlRule::class,
542 21
                        'pattern' => '.well-known/openid-configuration',
543 21
                        'route' => $this->id
544 21
                            . '/' . Oauth2WellKnownControllerInterface::CONTROLLER_NAME
545 21
                            . '/' . Oauth2WellKnownControllerInterface::ACTION_NAME_OPENID_CONFIGURATION,
546 21
                    ]),
547 21
                ]);
548
            }
549
        }
550
    }
551
552
    /**
553
     * Registers the translations for the module
554
     * @param bool $force Force the setting of the translations (even if they are already defined).
555
     * @since 1.0.0
556
     */
557 128
    public function registerTranslations($force = false)
558
    {
559 128
        if ($force || !array_key_exists('oauth2', Yii::$app->i18n->translations)) {
560 128
            Yii::$app->i18n->translations['oauth2'] = [
561 128
                'class' => PhpMessageSource::class,
562 128
                'sourceLanguage' => 'en-US',
563 128
                'basePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
564 128
                'fileMap' => [
565 128
                    'oauth2' => 'oauth2.php',
566 128
                ],
567 128
            ];
568
        }
569
    }
570
571
    /**
572
     * @param string $identifier The client identifier
573
     * @param string $name The (user-friendly) name of the client
574
     * @param int $grantTypes The grant types enabled for this client.
575
     *        Use bitwise `OR` to combine multiple types,
576
     *        e.g. `Oauth2Module::GRANT_TYPE_AUTH_CODE | Oauth2Module::GRANT_TYPE_REFRESH_TOKEN`
577
     * @param string|string[] $redirectURIs One or multiple redirect URIs for the client
578
     * @param int $type The client type (e.g. Confidential or Public)
579
     *        See `\rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface::TYPES` for possible values
580
     * @param string|null $secret The client secret in case the client `type` is `confidential`.
581
     * @param string|string[]|array[]|Oauth2ScopeInterface[]|null $scopes
582
     * @param int|null $userId
583
     * @return Oauth2ClientInterface
584
     * @throws InvalidConfigException
585
     * @throws \yii\db\Exception
586
     */
587 12
    public function createClient(
588
        $identifier,
589
        $name,
590
        $grantTypes,
591
        $redirectURIs,
592
        $type,
593
        $secret = null,
594
        $scopes = null,
595
        $userId = null,
596
        $endUsersMayAuthorizeClient = null,
597
        $skipAuthorizationIfScopeIsAllowed = null
598
    ) {
599 12
        if (!($this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER)) {
600 1
            throw new InvalidCallException('Oauth2 server role does not include authorization server.');
601
        }
602
603
        /** @var Oauth2ClientInterface $client */
604 11
        $client = Yii::createObject([
605 11
            'class' => Oauth2ClientInterface::class,
606 11
            'identifier' => $identifier,
607 11
            'type' => $type,
608 11
            'name' => $name,
609 11
            'redirectUri' => $redirectURIs,
610 11
            'grantTypes' => $grantTypes,
611 11
            'endUsersMayAuthorizeClient' => $endUsersMayAuthorizeClient,
612 11
            'skip_authorization_if_scope_is_allowed' => $skipAuthorizationIfScopeIsAllowed,
613 11
            'clientCredentialsGrantUserId' => $userId
614 11
        ]);
615
616 11
        $transaction = $client::getDb()->beginTransaction();
617
618
        try {
619 11
            if ($type == Oauth2ClientInterface::TYPE_CONFIDENTIAL) {
620 11
                $client->setSecret($secret, $this->getEncryptor());
621
            }
622
623 10
            $client->persist();
624
625 10
            if (!empty($scopes)) {
626 8
                if (is_string($scopes)) {
627 2
                    $scopes = explode(' ', $scopes);
628 6
                } elseif (!is_array($scopes)) {
0 ignored issues
show
introduced by
The condition is_array($scopes) is always true.
Loading history...
629 1
                    throw new InvalidArgumentException('$scopes must be a string or an array.');
630
                }
631
632 7
                foreach ($scopes as $key => $value) {
633
634 7
                    $scopeIdentifier = null;
635 7
                    $clientScopeConfig = [
636 7
                        'class' => Oauth2ClientScopeInterface::class,
637 7
                        'client_id' => $client->getPrimaryKey(),
638 7
                    ];
639
640 7
                    if (is_string($value)) {
641 3
                        $scopeIdentifier = $value;
642 4
                    } elseif ($value instanceof Oauth2ScopeInterface) {
643 2
                        $scopePk = $value->getPrimaryKey();
644 2
                        if ($scopePk) {
645 1
                            $clientScopeConfig = ArrayHelper::merge(
646 1
                                $clientScopeConfig,
647 1
                                ['scope_id' => $scopePk]
648 1
                            );
649
                        } else {
650 2
                            $scopeIdentifier = $value->getIdentifier();
651
                        }
652 2
                    } elseif(is_array($value)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after ELSEIF keyword; 0 found
Loading history...
653 1
                        $clientScopeConfig = ArrayHelper::merge(
654 1
                            $clientScopeConfig,
655 1
                            $value,
656 1
                        );
657 1
                        if (empty($clientScopeConfig['scope_id'])) {
658 1
                            $scopeIdentifier = $key;
659
                        }
660
                    } else {
661 1
                        throw new InvalidArgumentException(
662 1
                            'If $scopes is an array, its values must be a string, array or an instance of '
663 1
                            . Oauth2ScopeInterface::class. '.'
0 ignored issues
show
Coding Style introduced by
Expected at least 1 space before "."; 0 found
Loading history...
664 1
                        );
665
                    }
666
667 6
                    if (isset($scopeIdentifier)) {
668 5
                        $scope = $this->getScopeRepository()->findModelByIdentifier($scopeIdentifier);
669 5
                        if (empty($scope)) {
670 1
                            throw new InvalidArgumentException('No scope with identifier "'
671 1
                                . $scopeIdentifier . '" found.');
672
                        }
673 4
                        $clientScopeConfig['scope_id'] = $scope->getPrimaryKey();
674
                    } else {
675 2
                        if (empty($clientScopeConfig['scope_id'])) {
676 1
                            throw new InvalidArgumentException('Element ' . $key . ' in $scope should specify either the scope id or its identifier.');
677
                        }
678
                    }
679
680
                    /** @var Oauth2ClientScopeInterface $clientScope */
681 4
                    $clientScope = Yii::createObject($clientScopeConfig);
682 4
                    $clientScope->persist();
683
                }
684
            }
685
686 6
            $transaction->commit();
687 5
        } catch (\Exception $e) {
688 5
            $transaction->rollBack();
689 5
            throw $e;
690
        }
691
692 6
        return $client;
693
    }
694
695
    /**
696
     * @return CryptKey The private key of the server.
697
     * @throws InvalidConfigException
698
     * @since 1.0.0
699
     */
700 20
    public function getPrivateKey()
701
    {
702 20
        $privateKey = $this->privateKey;
703 20
        if (StringHelper::startsWith($privateKey, '@')) {
704 17
            $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

704
            $privateKey = 'file://' . /** @scrutinizer ignore-type */ Yii::getAlias($privateKey);
Loading history...
705
        }
706 20
        return Yii::createObject(CryptKey::class, [$privateKey, $this->privateKeyPassphrase]);
707
    }
708
709
    /**
710
     * @return CryptKey The public key of the server.
711
     * @throws InvalidConfigException
712
     * @since 1.0.0
713
     */
714 9
    public function getPublicKey()
715
    {
716 9
        $publicKey = $this->publicKey;
717 9
        if (StringHelper::startsWith($publicKey, '@')) {
718 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

718
            $publicKey = 'file://' . /** @scrutinizer ignore-type */ Yii::getAlias($publicKey);
Loading history...
719
        }
720 9
        return Yii::createObject(CryptKey::class, [$publicKey]);
721
    }
722
723
    /**
724
     * @return Oauth2AuthorizationServerInterface The authorization server.
725
     * @throws InvalidConfigException
726
     * @since 1.0.0
727
     */
728 25
    public function getAuthorizationServer()
729
    {
730 25
        if (!($this->serverRole & static::SERVER_ROLE_AUTHORIZATION_SERVER)) {
731 1
            throw new InvalidCallException('Oauth2 server role does not include authorization server.');
732
        }
733
734 24
        if (!$this->_authorizationServer) {
735 24
            $this->ensureProperties(static::REQUIRED_SETTINGS_AUTHORIZATION_SERVER);
736
737 19
            if (!$this->getEncryptor()->hasKey($this->defaultStorageEncryptionKey)) {
738 1
                throw new InvalidConfigException(
739 1
                    'Key "' . $this->defaultStorageEncryptionKey . '" is not set in $storageEncryptionKeys'
740 1
                );
741
            }
742
743
            /** @var Oauth2EncryptionKeyFactoryInterface $keyFactory */
744 17
            $keyFactory = Yii::createObject(Oauth2EncryptionKeyFactoryInterface::class);
745
            try {
746 17
                $codesEncryptionKey = $keyFactory->createFromAsciiSafeString($this->codesEncryptionKey);
747 1
            } catch (BadFormatException $e) {
748 1
                throw new InvalidConfigException(
749 1
                    '$codesEncryptionKey is malformed: ' . $e->getMessage(),
750 1
                    0,
751 1
                    $e
752 1
                );
753
            } catch (EnvironmentIsBrokenException $e) {
754
                throw new InvalidConfigException(
755
                    'Could not instantiate $codesEncryptionKey: ' . $e->getMessage(),
756
                    0,
757
                    $e
758
                );
759
            }
760
761 16
            $responseType = null;
762 16
            if ($this->enableOpenIdConnect) {
763 16
                $responseType = Yii::createObject(Oauth2OidcBearerTokenResponseInterface::class, [
764 16
                    $this,
765 16
                ]);
766
            }
767
768 16
            $this->_authorizationServer = Yii::createObject(Oauth2AuthorizationServerInterface::class, [
769 16
                $this->getClientRepository(),
770 16
                $this->getAccessTokenRepository(),
771 16
                $this->getScopeRepository(),
772 16
                $this->getPrivateKey(),
773 16
                $codesEncryptionKey,
774 16
                $responseType
775 16
            ]);
776
777 16
            if (!empty($this->grantTypes)) {
778 16
                $grantTypes = $this->grantTypes;
779
780 16
                if (is_callable($grantTypes)) {
781 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

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

992
        /** @scrutinizer ignore-call */ 
993
        $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...
993 5
        if (!($clientAuthorizationRequest instanceof Oauth2ClientAuthorizationRequestInterface)) {
994 2
            if (!empty($clientAuthorizationRequest)) {
995 1
                Yii::warning(
996 1
                    'Found a ClientAuthorizationRequestSession with key "' . $key
997 1
                        . '", but it\'s not a ' . Oauth2ClientAuthorizationRequestInterface::class
998 1
                );
999
            }
1000 2
            return null;
1001
        }
1002 5
        if ($clientAuthorizationRequest->getRequestId() !== $requestId) {
1003 1
            Yii::warning(
1004 1
                'Found a ClientAuthorizationRequestSession with key "' . $key
1005 1
                    . '", but its request id does not match "' . $requestId . '".'
1006 1
            );
1007 1
            return null;
1008
        }
1009 5
        $clientAuthorizationRequest->setModule($this);
1010
1011 5
        return $clientAuthorizationRequest;
1012
    }
1013
1014
    /**
1015
     * Stores the Client Authorization Request in the session.
1016
     * @param Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest
1017
     * @since 1.0.0
1018
     */
1019 8
    public function setClientAuthReqSession($clientAuthorizationRequest)
1020
    {
1021 8
        $requestId = $clientAuthorizationRequest->getRequestId();
1022 8
        if (empty($requestId)) {
1023 1
            throw new InvalidArgumentException('$scopeAuthorization must return a request id.');
1024
        }
1025 7
        $key = static::CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX . $requestId;
1026 7
        Yii::$app->session->set($key, $clientAuthorizationRequest);
1027
    }
1028
1029
    /**
1030
     * Stores whether the user was authenticated during the completion of the Client Authorization Request.
1031
     * @param string $clientAuthorizationRequestId
1032
     * @param bool $authenticatedDuringRequest
1033
     * @since 1.0.0
1034
     */
1035
    public function setUserAuthenticatedDuringClientAuthRequest(
1036
        $clientAuthorizationRequestId,
1037
        $authenticatedDuringRequest
1038
    ) {
1039
        $clientAuthorizationRequest = $this->getClientAuthReqSession($clientAuthorizationRequestId);
1040
        if ($clientAuthorizationRequest) {
1041
            $clientAuthorizationRequest->setUserAuthenticatedDuringRequest($authenticatedDuringRequest);
1042
            $this->setClientAuthReqSession($clientAuthorizationRequest);
1043
        }
1044
    }
1045
1046
    /**
1047
     * Stores the user identity selected during the completion of the Client Authorization Request.
1048
     * @param string $clientAuthorizationRequestId
1049
     * @param Oauth2UserInterface $userIdentity
1050
     * @since 1.0.0
1051
     */
1052
    public function setClientAuthRequestUserIdentity($clientAuthorizationRequestId, $userIdentity)
1053
    {
1054
        $clientAuthorizationRequest = $this->getClientAuthReqSession($clientAuthorizationRequestId);
1055
        if ($clientAuthorizationRequest) {
1056
            $clientAuthorizationRequest->setUserIdentity($userIdentity);
1057
            $this->setClientAuthReqSession($clientAuthorizationRequest);
1058
        }
1059
    }
1060
1061
    /**
1062
     * Clears a Client Authorization Request from the session storage.
1063
     * @param string $requestId
1064
     * @since 1.0.0
1065
     */
1066 2
    public function removeClientAuthReqSession($requestId)
1067
    {
1068 2
        if (empty($requestId)) {
1069 1
            throw new InvalidArgumentException('$requestId can not be empty.');
1070
        }
1071 1
        $key = static::CLIENT_AUTHORIZATION_REQUEST_SESSION_PREFIX . $requestId;
1072 1
        Yii::$app->session->remove($key);
1073
    }
1074
1075
    /**
1076
     * Generates a redirect Response when the Client Authorization Request is completed.
1077
     * @param Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest
1078
     * @return Response
1079
     * @since 1.0.0
1080
     */
1081 1
    public function generateClientAuthReqCompledRedirectResponse($clientAuthorizationRequest)
1082
    {
1083 1
        $clientAuthorizationRequest->processAuthorization();
1084 1
        $this->setClientAuthReqSession($clientAuthorizationRequest);
1085 1
        return Yii::$app->response->redirect($clientAuthorizationRequest->getAuthorizationRequestUrl());
1086
    }
1087
1088
    /**
1089
     * @return IdentityInterface|Oauth2UserInterface|Oauth2OidcUserInterface|null
1090
     * @throws InvalidConfigException
1091
     * @since 1.0.0
1092
     */
1093 5
    public function getUserIdentity()
1094
    {
1095 5
        $user = Yii::$app->user->identity;
1096 5
        if (!empty($user) && !($user instanceof Oauth2UserInterface)) {
1097 1
            throw new InvalidConfigException(
1098 1
                'Yii::$app->user->identity (currently ' . get_class($user)
1099 1
                    . ') must implement ' . Oauth2UserInterface::class
1100 1
            );
1101
        }
1102 4
        return $user;
1103
    }
1104
1105
    /**
1106
     * Validates a bearer token authenticated request. Note: this method does not return a result but will throw
1107
     * an exception when the authentication fails.
1108
     * @throws InvalidConfigException
1109
     * @throws Oauth2ServerException
1110
     * @since 1.0.0
1111
     */
1112 3
    public function validateAuthenticatedRequest()
1113
    {
1114 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

1114
        $psr7Request = Psr7Helper::yiiToPsr7Request(/** @scrutinizer ignore-type */ Yii::$app->request);
Loading history...
1115
1116 3
        $psr7Request = $this->getResourceServer()->validateAuthenticatedRequest($psr7Request);
1117
1118 3
        $this->_oauthClaims = $psr7Request->getAttributes();
1119 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...
1120
    }
1121
1122
    /**
1123
     * Find a user identity bases on an access token.
1124
     * Note: validateAuthenticatedRequest() must be called before this method is called.
1125
     * @param string $token
1126
     * @param string $type
1127
     * @return Oauth2UserInterface|null
1128
     * @throws InvalidConfigException
1129
     * @throws Oauth2ServerException
1130
     * @see validateAuthenticatedRequest()
1131
     * @since 1.0.0
1132
     */
1133 4
    public function findIdentityByAccessToken($token, $type)
1134
    {
1135 4
        if (!is_a($type, Oauth2HttpBearerAuthInterface::class, true)) {
1136 1
            throw new InvalidCallException($type . ' must implement ' . Oauth2HttpBearerAuthInterface::class);
1137
        }
1138
1139
        if (
1140 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

1140
            !preg_match('/^Bearer\s+(.*?)$/', /** @scrutinizer ignore-type */ $this->_oauthClaimsAuthorizationHeader, $matches)
Loading history...
1141 3
            || !Yii::$app->security->compareString($matches[1], $token)
1142
        ) {
1143 1
            throw new InvalidCallException(
1144 1
                'validateAuthenticatedRequest() must be called before findIdentityByAccessToken().'
1145 1
            );
1146
        }
1147
1148 2
        $userId = $this->getRequestOauthUserId();
1149 2
        if (empty($userId)) {
1150 1
            return null;
1151
        }
1152
1153 1
        return $this->identityClass::findIdentity($userId);
1154
    }
1155
1156
    /**
1157
     * Generate a "Personal Access Token" (PAT) which can be used as an alternative to using passwords
1158
     * for authentication (e.g. when using an API or command line).
1159
     *
1160
     * Note: Personal Access Tokens are intended to access resources on behalf users themselves.
1161
     *       To grant access to resources on behalf of an organization, or for long-lived integrations,
1162
     *       you most likely want to define an Oauth2 Client with the "Client Credentials" grant
1163
     *       (https://oauth.net/2/grant-types/client-credentials).
1164
     *
1165
     * @param string $clientIdentifier The Oauth2 client identifier for which the PAT should be generated.
1166
     * @param int|string $userIdentifier The identifier (primary key) of the user for which the PAT should be generated.
1167
     * @param Oauth2ScopeInterface[]|string[]|string|null $scope The Access Token scope.
1168
     * @param string|true|null $clientSecret If the client is a "confidential" client the secret is required.
1169
     *        If the boolean value `true` is passed, the client secret is automatically injected.
1170
     * @return Oauth2AccessTokenData
1171
     */
1172 3
    public function generatePersonalAccessToken($clientIdentifier, $userIdentifier, $scope = null, $clientSecret = null)
1173
    {
1174 3
        if (is_array($scope)) {
1175 2
            $scopeIdentifiers = [];
1176 2
            foreach ($scope as $scopeItem) {
1177 2
                if (is_string($scopeItem)) {
1178 1
                    $scopeIdentifiers[] = $scopeItem;
1179 1
                } elseif ($scopeItem instanceof Oauth2ScopeInterface) {
1180 1
                    $scopeIdentifiers[] = $scopeItem->getIdentifier();
1181
                } else {
1182
                    throw new InvalidArgumentException('If $scope is an array its elements must be either'
1183
                        . ' a string or an instance of ' . Oauth2ScopeInterface::class);
1184
                }
1185
            }
1186 2
            $scope = implode(' ', $scopeIdentifiers);
1187
        }
1188
1189 3
        if ($clientSecret === true) {
1190
            /** @var Oauth2ClientInterface $client */
1191 3
            $client = $this->getClientRepository()->findModelByIdentifier($clientIdentifier);
1192 3
            if ($client && $client->isConfidential()) {
1193 3
                $clientSecret = $client->getDecryptedSecret($this->getEncryptor());
1194
            } else {
1195
                $clientSecret = null;
1196
            }
1197
        }
1198
1199 3
        $request = (new Psr7ServerRequest('POST', ''))->withParsedBody([
1200 3
            'grant_type' => static::GRANT_TYPE_IDENTIFIER_PERSONAL_ACCESS_TOKEN,
1201 3
            'client_id' => $clientIdentifier,
1202 3
            'client_secret' => $clientSecret,
1203 3
            'user_id' => $userIdentifier,
1204 3
            'scope' => $scope,
1205 3
        ]);
1206
1207 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

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