Passed
Pull Request — master (#1473)
by
unknown
35:44
created

BearerTokenValidator::validateJwt()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 38
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 8.064

Importance

Changes 0
Metric Value
cc 8
eloc 20
nc 7
nop 3
dl 0
loc 38
ccs 9
cts 10
cp 0.9
crap 8.064
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @author      Alex Bilbie <[email protected]>
5
 * @copyright   Copyright (c) Alex Bilbie
6
 * @license     http://mit-license.org/
7
 *
8
 * @link        https://github.com/thephpleague/oauth2-server
9
 */
10
11
declare(strict_types=1);
12
13
namespace League\OAuth2\Server\AuthorizationValidators;
14
15
use DateInterval;
16
use DateTimeZone;
17
use Lcobucci\Clock\SystemClock;
0 ignored issues
show
Bug introduced by
The type Lcobucci\Clock\SystemClock was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Lcobucci\JWT\Configuration;
19
use Lcobucci\JWT\Exception;
20
use Lcobucci\JWT\Signer\Key\InMemory;
21
use Lcobucci\JWT\Signer\Rsa\Sha256;
22
use Lcobucci\JWT\UnencryptedToken;
23
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
24
use Lcobucci\JWT\Validation\Constraint\SignedWith;
25
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
26
use League\OAuth2\Server\CryptKeyInterface;
27
use League\OAuth2\Server\CryptTrait;
28
use League\OAuth2\Server\Exception\OAuthServerException;
29
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
30
use Psr\Http\Message\ServerRequestInterface;
31
use RuntimeException;
32
33
use function date_default_timezone_get;
34
use function preg_replace;
35
use function trim;
36
37
class BearerTokenValidator implements AuthorizationValidatorInterface, JwtValidatorInterface
38
{
39
    use CryptTrait;
40
41
    protected CryptKeyInterface $publicKey;
42
43
    private Configuration $jwtConfiguration;
44
45 14
    public function __construct(private AccessTokenRepositoryInterface $accessTokenRepository, private ?DateInterval $jwtValidAtDateLeeway = null)
46
    {
47 14
    }
48
49
    /**
50
     * Set the public key
51
     */
52 14
    public function setPublicKey(CryptKeyInterface $key): void
53
    {
54 14
        $this->publicKey = $key;
55
56 14
        $this->initJwtConfiguration();
57
    }
58
59
    /**
60
     * Initialise the JWT configuration.
61
     */
62 14
    private function initJwtConfiguration(): void
63
    {
64 14
        $this->jwtConfiguration = Configuration::forSymmetricSigner(
65 14
            new Sha256(),
66 14
            InMemory::plainText('empty', 'empty')
67 14
        );
68
69 14
        $clock = new SystemClock(new DateTimeZone(date_default_timezone_get()));
70
71 14
        $publicKeyContents = $this->publicKey->getKeyContents();
72
73 14
        if ($publicKeyContents === '') {
74
            throw new RuntimeException('Public key is empty');
75
        }
76
77
        // TODO: next major release: replace deprecated method and remove phpstan ignored error
78 14
        $this->jwtConfiguration->setValidationConstraints(
0 ignored issues
show
Deprecated Code introduced by
The function Lcobucci\JWT\Configurati...ValidationConstraints() has been deprecated: Deprecated since v5.5, please use {@see self::withValidationConstraints()} instead ( Ignorable by Annotation )

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

78
        /** @scrutinizer ignore-deprecated */ $this->jwtConfiguration->setValidationConstraints(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
79 14
            new LooseValidAt($clock, $this->jwtValidAtDateLeeway),
80 14
            new SignedWith(
81 14
                new Sha256(),
82 14
                InMemory::plainText($publicKeyContents, $this->publicKey->getPassPhrase() ?? '')
83 14
            )
84 14
        );
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 14
    public function validateAuthorization(ServerRequestInterface $request): ServerRequestInterface
91
    {
92 14
        if ($request->hasHeader('authorization') === false) {
93 1
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
94
        }
95
96 13
        $header = $request->getHeader('authorization');
97 13
        $jwt = trim((string) preg_replace('/^\s*Bearer\s/i', '', $header[0]));
98
99 13
        if ($jwt === '') {
100 1
            throw OAuthServerException::accessDenied('Missing "Bearer" token');
101
        }
102
103
        $claims = $this->validateJwt($request, $jwt);
104
105 12
        // Return the request with additional attributes
106 2
        return $request
107 2
            ->withAttribute('oauth_access_token_id', $claims['jti'] ?? null)
108
            ->withAttribute('oauth_client_id', $claims['aud'][0] ?? null)
109
            ->withAttribute('oauth_user_id', $claims['sub'] ?? null)
110
            ->withAttribute('oauth_scopes', $claims['scopes'] ?? null);
111
    }
112 10
113 10
    /**
114 4
     * {@inheritdoc}
115 4
     */
116
    public function validateJwt(ServerRequestInterface $request, string $jwt, ?string $clientId = null): array
117
    {
118 6
        try {
119
            // Attempt to parse the JWT
120
            $token = $this->jwtConfiguration->parser()->parse($jwt);
121
        } catch (Exception $exception) {
122 6
            throw OAuthServerException::accessDenied($exception->getMessage(), null, $exception);
123
        }
124
125 6
        try {
126 1
            // Attempt to validate the JWT
127
            $constraints = $this->jwtConfiguration->validationConstraints();
128
            $this->jwtConfiguration->validator()->assert($token, ...$constraints);
129
        } catch (RequiredConstraintsViolated $exception) {
130 5
            throw OAuthServerException::accessDenied('Access token could not be verified', null, $exception);
131 5
        }
132 5
133 5
        if (!$token instanceof UnencryptedToken) {
134 5
            throw OAuthServerException::accessDenied('Access token is not an instance of UnencryptedToken');
135
        }
136
137
        $claims = $token->claims();
138
139
        // Check if token is linked to the client
140
        if (
141
            $clientId !== null &&
142
            $claims->get('client_id') !== $clientId &&
143
            !$token->isPermittedFor($clientId)
144
        ) {
145
            throw OAuthServerException::accessDenied('Access token is not linked to client');
146
        }
147
148
        // Check if token has been revoked
149
        if ($this->accessTokenRepository->isAccessTokenRevoked($claims->get('jti'))) {
150
            throw OAuthServerException::accessDenied('Access token has been revoked');
151
        }
152
153
        return $claims->all();
154
    }
155
}
156