BearerTokenValidator::validateAuthorization()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 45
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7.0035

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 25
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 45
ccs 23
cts 24
cp 0.9583
crap 7.0035
rs 8.5866
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;
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
38
{
39
    use CryptTrait;
40
41
    protected CryptKeyInterface $publicKey;
42
43
    private Configuration $jwtConfiguration;
44
45 13
    public function __construct(private AccessTokenRepositoryInterface $accessTokenRepository, private ?DateInterval $jwtValidAtDateLeeway = null)
46
    {
47 13
    }
48
49
    /**
50
     * Set the public key
51
     */
52 13
    public function setPublicKey(CryptKeyInterface $key): void
53
    {
54 13
        $this->publicKey = $key;
55
56 13
        $this->initJwtConfiguration();
57
    }
58
59
    /**
60
     * Initialise the JWT configuration.
61
     */
62 13
    private function initJwtConfiguration(): void
63
    {
64 13
        $this->jwtConfiguration = Configuration::forSymmetricSigner(
65 13
            new Sha256(),
66 13
            InMemory::plainText('empty', 'empty')
67 13
        );
68
69 13
        $clock = new SystemClock(new DateTimeZone(date_default_timezone_get()));
70
71 13
        $publicKeyContents = $this->publicKey->getKeyContents();
72
73 13
        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 13
        $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 13
            new LooseValidAt($clock, $this->jwtValidAtDateLeeway),
80 13
            new SignedWith(
81 13
                new Sha256(),
82 13
                InMemory::plainText($publicKeyContents, $this->publicKey->getPassPhrase() ?? '')
83 13
            )
84 13
        );
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 13
    public function validateAuthorization(ServerRequestInterface $request): ServerRequestInterface
91
    {
92 13
        if ($request->hasHeader('authorization') === false) {
93 1
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
94
        }
95
96 12
        $header = $request->getHeader('authorization');
97 12
        $jwt = trim((string) preg_replace('/^\s*Bearer\s/', '', $header[0]));
98
99 12
        if ($jwt === '') {
100 1
            throw OAuthServerException::accessDenied('Missing "Bearer" token');
101
        }
102
103
        try {
104
            // Attempt to parse the JWT
105 11
            $token = $this->jwtConfiguration->parser()->parse($jwt);
106 2
        } catch (Exception $exception) {
107 2
            throw OAuthServerException::accessDenied($exception->getMessage(), null, $exception);
108
        }
109
110
        try {
111
            // Attempt to validate the JWT
112 9
            $constraints = $this->jwtConfiguration->validationConstraints();
113 9
            $this->jwtConfiguration->validator()->assert($token, ...$constraints);
114 4
        } catch (RequiredConstraintsViolated $exception) {
115 4
            throw OAuthServerException::accessDenied('Access token could not be verified', null, $exception);
116
        }
117
118 5
        if (!$token instanceof UnencryptedToken) {
119
            throw OAuthServerException::accessDenied('Access token is not an instance of UnencryptedToken');
120
        }
121
122 5
        $claims = $token->claims();
123
124
        // Check if token has been revoked
125 5
        if ($this->accessTokenRepository->isAccessTokenRevoked($claims->get('jti'))) {
126 1
            throw OAuthServerException::accessDenied('Access token has been revoked');
127
        }
128
129
        // Return the request with additional attributes
130 4
        return $request
131 4
            ->withAttribute('oauth_access_token_id', $claims->get('jti'))
132 4
            ->withAttribute('oauth_client_id', $claims->get('aud')[0])
133 4
            ->withAttribute('oauth_user_id', $claims->get('sub'))
134 4
            ->withAttribute('oauth_scopes', $claims->get('scopes'));
135
    }
136
}
137