| Total Complexity | 50 |
| Total Lines | 422 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like OpenIdConnect often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use OpenIdConnect, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 56 | final class OpenIdConnect extends OAuth2 |
||
| 57 | { |
||
| 58 | protected ?string $scope = 'openid'; |
||
| 59 | /** |
||
| 60 | * @var string OpenID Issuer (provider) base URL, e.g. `https://example.com`. |
||
| 61 | */ |
||
| 62 | private string $issuerUrl; |
||
| 63 | /** |
||
| 64 | * @var bool whether to validate/decrypt JWS received with Auth token. |
||
| 65 | * Note: this functionality requires `web-token/jwt-checker`, `web-token/jwt-key-mgmt`, `web-token/jwt-signature` |
||
| 66 | * composer package to be installed. You can disable this option in case of usage of trusted OpenIDConnect provider, |
||
| 67 | * however this violates the protocol rules, so you are doing it on your own risk. |
||
| 68 | */ |
||
| 69 | private bool $validateJws = true; |
||
| 70 | /** |
||
| 71 | * @var array JWS algorithms, which are allowed to be used. |
||
| 72 | * These are used by `web-token` library for JWS validation/decryption. |
||
| 73 | * Make sure to install `web-token/jwt-signature-algorithm-hmac`, `web-token/jwt-signature-algorithm-ecdsa` |
||
| 74 | * and `web-token/jwt-signature-algorithm-rsa` packages that support the particular algorithm before adding it here. |
||
| 75 | */ |
||
| 76 | private array $allowedJwsAlgorithms = [ |
||
| 77 | 'HS256', |
||
| 78 | 'HS384', |
||
| 79 | 'HS512', |
||
| 80 | 'ES256', |
||
| 81 | 'ES384', |
||
| 82 | 'ES512', |
||
| 83 | 'RS256', |
||
| 84 | 'RS384', |
||
| 85 | 'RS512', |
||
| 86 | 'PS256', |
||
| 87 | 'PS384', |
||
| 88 | 'PS512', |
||
| 89 | ]; |
||
| 90 | |||
| 91 | /** |
||
| 92 | * @var string the prefix for the key used to store {@see configParams} data in cache. |
||
| 93 | * Actual cache key will be formed addition {@see id} value to it. |
||
| 94 | * |
||
| 95 | * @see cache |
||
| 96 | */ |
||
| 97 | private string $configParamsCacheKeyPrefix = 'config-params-'; |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @var bool|null whether to use and validate auth 'nonce' parameter in authentication flow. |
||
| 101 | * The option is used for preventing replay attacks. |
||
| 102 | */ |
||
| 103 | private ?bool $validateAuthNonce; |
||
| 104 | |||
| 105 | /** |
||
| 106 | * @var array OpenID provider configuration parameters. |
||
| 107 | */ |
||
| 108 | private array $configParams = []; |
||
| 109 | private CacheInterface $cache; |
||
| 110 | private string $name; |
||
| 111 | private string $title; |
||
| 112 | |||
| 113 | /** |
||
| 114 | * @var JWSLoader JSON Web Signature |
||
| 115 | */ |
||
| 116 | private JWSLoader $jwsLoader; |
||
| 117 | /** |
||
| 118 | * @var JWKSet Key Set |
||
| 119 | */ |
||
| 120 | private JWKSet $jwkSet; |
||
| 121 | |||
| 122 | /** |
||
| 123 | * OpenIdConnect constructor. |
||
| 124 | * |
||
| 125 | * @param string|null $endpoint |
||
| 126 | * @param $name |
||
| 127 | * @param $title |
||
| 128 | * @param ClientInterface $httpClient |
||
| 129 | * @param RequestFactoryInterface $requestFactory |
||
| 130 | * @param CacheInterface $cache |
||
| 131 | * @param StateStorageInterface $stateStorage |
||
| 132 | * @param SessionInterface $session |
||
| 133 | */ |
||
| 134 | public function __construct( |
||
| 135 | $name, |
||
| 136 | $title, |
||
| 137 | ClientInterface $httpClient, |
||
| 138 | RequestFactoryInterface $requestFactory, |
||
| 139 | CacheInterface $cache, |
||
| 140 | StateStorageInterface $stateStorage, |
||
| 141 | SessionInterface $session, |
||
| 142 | FactoryInterface $factory |
||
| 143 | ) { |
||
| 144 | $this->name = $name; |
||
| 145 | $this->title = $title; |
||
| 146 | $this->cache = $cache; |
||
| 147 | parent::__construct($httpClient, $requestFactory, $stateStorage, $session, $factory); |
||
| 148 | } |
||
| 149 | |||
| 150 | public function buildAuthUrl( |
||
| 151 | ServerRequestInterface $incomingRequest, |
||
| 152 | array $params = [] |
||
| 153 | ): string { |
||
| 154 | if ($this->authUrl === null) { |
||
| 155 | $this->authUrl = $this->getConfigParam('authorization_endpoint'); |
||
| 156 | } |
||
| 157 | return parent::buildAuthUrl($incomingRequest, $params); |
||
| 158 | } |
||
| 159 | |||
| 160 | /** |
||
| 161 | * Returns particular configuration parameter value. |
||
| 162 | * |
||
| 163 | * @param string $name configuration parameter name. |
||
| 164 | * |
||
| 165 | * @throws InvalidConfigException |
||
| 166 | * @throws InvalidArgumentException |
||
| 167 | * |
||
| 168 | * @return mixed configuration parameter value. |
||
| 169 | */ |
||
| 170 | public function getConfigParam($name) |
||
| 171 | { |
||
| 172 | $params = $this->getConfigParams(); |
||
| 173 | return $params[$name]; |
||
| 174 | } |
||
| 175 | |||
| 176 | /** |
||
| 177 | * @throws InvalidConfigException |
||
| 178 | * @throws InvalidArgumentException |
||
| 179 | * |
||
| 180 | * @return array OpenID provider configuration parameters. |
||
| 181 | */ |
||
| 182 | public function getConfigParams(): array |
||
| 183 | { |
||
| 184 | if ($this->configParams === null) { |
||
| 185 | $cacheKey = $this->configParamsCacheKeyPrefix . $this->getName(); |
||
| 186 | if (($configParams = $this->cache->get($cacheKey)) === null) { |
||
| 187 | $configParams = $this->discoverConfig(); |
||
| 188 | } |
||
| 189 | |||
| 190 | $this->configParams = $configParams; |
||
| 191 | $this->cache->set($cacheKey, $configParams); |
||
| 192 | } |
||
| 193 | return $this->configParams; |
||
| 194 | } |
||
| 195 | |||
| 196 | /** |
||
| 197 | * @return string service name. |
||
| 198 | */ |
||
| 199 | public function getName(): string |
||
| 200 | { |
||
| 201 | return 'open_id_connect'; |
||
| 202 | } |
||
| 203 | |||
| 204 | /** |
||
| 205 | * Discovers OpenID Provider configuration parameters. |
||
| 206 | * |
||
| 207 | * @throws InvalidConfigException |
||
| 208 | * |
||
| 209 | * @return array OpenID Provider configuration parameters. |
||
| 210 | */ |
||
| 211 | private function discoverConfig(): array |
||
| 212 | { |
||
| 213 | if ($this->issuerUrl === null) { |
||
| 214 | throw new InvalidConfigException('Cannot discover config because issuer URL is not set.'); |
||
| 215 | } |
||
| 216 | $configUrl = $this->issuerUrl . '/.well-known/openid-configuration'; |
||
| 217 | $request = $this->createRequest('GET', $configUrl); |
||
| 218 | $response = $this->sendRequest($request); |
||
| 219 | |||
| 220 | return Json::decode($response->getBody()->getContents()); |
||
| 221 | } |
||
| 222 | |||
| 223 | public function fetchAccessToken(ServerRequestInterface $request, $authCode, array $params = []): OAuthToken |
||
| 224 | { |
||
| 225 | if ($this->tokenUrl === null) { |
||
| 226 | $this->tokenUrl = $this->getConfigParam('token_endpoint'); |
||
| 227 | } |
||
| 228 | |||
| 229 | if (!isset($params['nonce']) && $this->getValidateAuthNonce()) { |
||
| 230 | $nonce = $this->generateAuthNonce(); |
||
| 231 | $this->setState('authNonce', $nonce); |
||
| 232 | $params['nonce'] = $nonce; |
||
| 233 | } |
||
| 234 | |||
| 235 | return parent::fetchAccessToken($request, $authCode, $params); |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * @throws InvalidConfigException |
||
| 240 | * @throws InvalidArgumentException |
||
| 241 | * |
||
| 242 | * @return bool whether to use and validate auth 'nonce' parameter in authentication flow. |
||
| 243 | */ |
||
| 244 | public function getValidateAuthNonce(): bool |
||
| 245 | { |
||
| 246 | if ($this->validateAuthNonce === null) { |
||
| 247 | $this->validateAuthNonce = $this->validateJws && in_array( |
||
| 248 | 'nonce', |
||
| 249 | $this->getConfigParam('claims_supported'), |
||
| 250 | true |
||
| 251 | ); |
||
| 252 | } |
||
| 253 | return $this->validateAuthNonce; |
||
| 254 | } |
||
| 255 | |||
| 256 | /** |
||
| 257 | * @param bool $validateAuthNonce whether to use and validate auth 'nonce' parameter in authentication flow. |
||
| 258 | */ |
||
| 259 | public function setValidateAuthNonce($validateAuthNonce): void |
||
| 260 | { |
||
| 261 | $this->validateAuthNonce = $validateAuthNonce; |
||
| 262 | } |
||
| 263 | |||
| 264 | /** |
||
| 265 | * Generates the auth nonce value. |
||
| 266 | * |
||
| 267 | * @throws Exception |
||
| 268 | * |
||
| 269 | * @return string auth nonce value. |
||
| 270 | */ |
||
| 271 | protected function generateAuthNonce(): string |
||
| 272 | { |
||
| 273 | return Random::string(); |
||
| 274 | } |
||
| 275 | |||
| 276 | public function refreshAccessToken(OAuthToken $token): OAuthToken |
||
| 277 | { |
||
| 278 | if ($this->tokenUrl === null) { |
||
| 279 | $this->tokenUrl = $this->getConfigParam('token_endpoint'); |
||
| 280 | } |
||
| 281 | return parent::refreshAccessToken($token); |
||
| 282 | } |
||
| 283 | |||
| 284 | /** |
||
| 285 | * @return string service title. |
||
| 286 | */ |
||
| 287 | public function getTitle(): string |
||
| 288 | { |
||
| 289 | return 'OpenID Connect'; |
||
| 290 | } |
||
| 291 | |||
| 292 | public function setIssuerUrl(string $url): void |
||
| 293 | { |
||
| 294 | $this->issuerUrl = rtrim($url, '/'); |
||
| 295 | } |
||
| 296 | |||
| 297 | protected function initUserAttributes(): array |
||
| 298 | { |
||
| 299 | return $this->api($this->getConfigParam('userinfo_endpoint'), 'GET'); |
||
| 300 | } |
||
| 301 | |||
| 302 | protected function applyClientCredentialsToRequest(RequestInterface $request): RequestInterface |
||
| 303 | { |
||
| 304 | $supportedAuthMethods = $this->getConfigParam('token_endpoint_auth_methods_supported'); |
||
| 305 | |||
| 306 | if (in_array('client_secret_basic', $supportedAuthMethods, true)) { |
||
| 307 | $request = $request->withHeader( |
||
| 308 | 'Authorization', |
||
| 309 | 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret) |
||
| 310 | ); |
||
| 311 | } elseif (in_array('client_secret_post', $supportedAuthMethods, true)) { |
||
| 312 | $request = RequestUtil::addParams( |
||
| 313 | $request, |
||
| 314 | [ |
||
| 315 | 'client_id' => $this->clientId, |
||
| 316 | 'client_secret' => $this->clientSecret, |
||
| 317 | ] |
||
| 318 | ); |
||
| 319 | } elseif (in_array('client_secret_jwt', $supportedAuthMethods, true)) { |
||
| 320 | $header = [ |
||
| 321 | 'typ' => 'JWT', |
||
| 322 | 'alg' => 'HS256', |
||
| 323 | ]; |
||
| 324 | $payload = [ |
||
| 325 | 'iss' => $this->clientId, |
||
| 326 | 'sub' => $this->clientId, |
||
| 327 | 'aud' => $this->tokenUrl, |
||
| 328 | 'jti' => $this->generateAuthNonce(), |
||
| 329 | 'iat' => time(), |
||
| 330 | 'exp' => time() + 3600, |
||
| 331 | ]; |
||
| 332 | |||
| 333 | $signatureBaseString = base64_encode(Json::encode($header)) . '.' . base64_encode(Json::encode($payload)); |
||
| 334 | $signatureMethod = new HmacSha('sha256'); |
||
| 335 | $signature = $signatureMethod->generateSignature($signatureBaseString, $this->clientSecret); |
||
| 336 | |||
| 337 | $assertion = $signatureBaseString . '.' . $signature; |
||
| 338 | |||
| 339 | $request = RequestUtil::addParams( |
||
| 340 | $request, |
||
| 341 | [ |
||
| 342 | 'assertion' => $assertion, |
||
| 343 | ] |
||
| 344 | ); |
||
| 345 | } else { |
||
| 346 | throw new InvalidConfigException( |
||
| 347 | 'Unable to authenticate request: none of following auth methods is supported: ' . implode( |
||
| 348 | ', ', |
||
| 349 | $supportedAuthMethods |
||
| 350 | ) |
||
| 351 | ); |
||
| 352 | } |
||
| 353 | return $request; |
||
| 354 | } |
||
| 355 | |||
| 356 | protected function defaultReturnUrl(ServerRequestInterface $request): string |
||
| 357 | { |
||
| 358 | $params = $request->getQueryParams(); |
||
| 359 | // OAuth2 specifics : |
||
| 360 | unset($params['code'], $params['state'], $params['nonce'], $params['authuser'], $params['session_state'], $params['prompt']); |
||
| 361 | // OpenIdConnect specifics : |
||
| 362 | |||
| 363 | |||
| 364 | return $request->getUri()->withQuery(http_build_query($params, '', '&', PHP_QUERY_RFC3986))->__toString(); |
||
| 365 | } |
||
| 366 | |||
| 367 | protected function createToken(array $tokenConfig = []): OAuthToken |
||
| 368 | { |
||
| 369 | if ($this->validateJws) { |
||
| 370 | $jwsData = $this->loadJws($tokenConfig['params']['id_token']); |
||
| 371 | $this->validateClaims($jwsData); |
||
| 372 | $tokenConfig['params'] = array_merge($tokenConfig['params'], $jwsData); |
||
| 373 | |||
| 374 | if ($this->getValidateAuthNonce()) { |
||
| 375 | $authNonce = $this->getState('authNonce'); |
||
| 376 | if (!isset($jwsData['nonce']) || empty($authNonce) || strcmp($jwsData['nonce'], $authNonce) !== 0) { |
||
| 377 | throw new HttpException('Invalid auth nonce', 400); |
||
| 378 | } |
||
| 379 | |||
| 380 | $this->removeState('authNonce'); |
||
| 381 | } |
||
| 382 | } |
||
| 383 | |||
| 384 | return parent::createToken($tokenConfig); |
||
| 385 | } |
||
| 386 | |||
| 387 | /** |
||
| 388 | * Decrypts/validates JWS, returning related data. |
||
| 389 | * |
||
| 390 | * @param string $jws raw JWS input. |
||
| 391 | * |
||
| 392 | * @throws HttpException on invalid JWS signature. |
||
| 393 | * @throws InvalidArgumentException |
||
| 394 | * |
||
| 395 | * @return array JWS underlying data. |
||
| 396 | */ |
||
| 397 | protected function loadJws(string $jws): array |
||
| 398 | { |
||
| 399 | try { |
||
| 400 | $jwsLoader = $this->getJwsLoader(); |
||
| 401 | $signature = null; |
||
| 402 | $jwsVerified = $jwsLoader->loadAndVerifyWithKeySet($jws, $this->getJwkSet(), $signature); |
||
| 403 | return Json::decode($jwsVerified->getPayload()); |
||
| 404 | } catch (Exception $e) { |
||
| 405 | $message = YII_DEBUG ? 'Unable to verify JWS: ' . $e->getMessage() : 'Invalid JWS'; |
||
| 406 | throw new HttpException($message, $e->getCode(), $e); |
||
| 407 | } |
||
| 408 | } |
||
| 409 | |||
| 410 | /** |
||
| 411 | * Return JWSLoader that validate the JWS token. |
||
| 412 | * |
||
| 413 | * @throws InvalidConfigException on invalid algorithm provide in configuration. |
||
| 414 | * |
||
| 415 | * @return JWSLoader to do token validation. |
||
| 416 | */ |
||
| 417 | protected function getJwsLoader(): JWSLoader |
||
| 438 | } |
||
| 439 | |||
| 440 | /** |
||
| 441 | * Return JwkSet, returning related data. |
||
| 442 | * |
||
| 443 | * @throws InvalidConfigException |
||
| 444 | * @throws InvalidArgumentException |
||
| 445 | * |
||
| 446 | * @return JWKSet object represents a key set. |
||
| 447 | */ |
||
| 448 | protected function getJwkSet(): JWKSet |
||
| 449 | { |
||
| 450 | if ($this->jwkSet === null) { |
||
| 451 | $cacheKey = $this->configParamsCacheKeyPrefix . 'jwkSet'; |
||
| 452 | if (($jwkSet = $this->cache->get($cacheKey)) === false) { |
||
| 453 | $request = $this->createRequest('GET', $this->getConfigParam('jwks_uri')); |
||
| 454 | $response = $this->sendRequest($request); |
||
| 455 | $jwkSet = JWKFactory::createFromValues($response); |
||
| 456 | } |
||
| 457 | |||
| 458 | $this->jwkSet = $jwkSet; |
||
| 459 | $this->cache->set($cacheKey, $jwkSet); |
||
| 460 | } |
||
| 461 | return $this->jwkSet; |
||
| 462 | } |
||
| 463 | |||
| 464 | /** |
||
| 465 | * Validates the claims data received from OpenID provider. |
||
| 466 | * |
||
| 467 | * @param array $claims claims data. |
||
| 468 | * |
||
| 469 | * @throws HttpException on invalid claims. |
||
| 470 | */ |
||
| 471 | protected function validateClaims(array $claims): void |
||
| 478 | } |
||
| 479 | } |
||
| 480 | } |
||
| 481 |
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths