Passed
Push — master ( d6e0b3...82e7b7 )
by Andrew
07:05 queued 11s
created

BearerTokenValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * @author      Alex Bilbie <[email protected]>
4
 * @copyright   Copyright (c) Alex Bilbie
5
 * @license     http://mit-license.org/
6
 *
7
 * @link        https://github.com/thephpleague/oauth2-server
8
 */
9
10
namespace League\OAuth2\Server\AuthorizationValidators;
11
12
use DateTimeZone;
13
use Lcobucci\Clock\SystemClock;
14
use Lcobucci\JWT\Configuration;
15
use Lcobucci\JWT\Signer\Key\InMemory;
16
use Lcobucci\JWT\Signer\Key\LocalFileReference;
17
use Lcobucci\JWT\Signer\Rsa\Sha256;
18
use Lcobucci\JWT\Validation\Constraint\SignedWith;
19
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
20
use Lcobucci\JWT\Validation\Constraint\ValidAt;
21
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
22
use League\OAuth2\Server\CryptKey;
23
use League\OAuth2\Server\CryptTrait;
24
use League\OAuth2\Server\Exception\OAuthServerException;
25
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
26
use Psr\Http\Message\ServerRequestInterface;
27
28
class BearerTokenValidator implements AuthorizationValidatorInterface
29
{
30
    use CryptTrait;
31
32
    /**
33
     * @var AccessTokenRepositoryInterface
34
     */
35
    private $accessTokenRepository;
36
37
    /**
38
     * @var CryptKey
39
     */
40
    protected $publicKey;
41
42
    /**
43
     * @var Configuration
44
     */
45
    private $jwtConfiguration;
46
47
    /**
48
     * @param AccessTokenRepositoryInterface $accessTokenRepository
49
     */
50 11
    public function __construct(AccessTokenRepositoryInterface $accessTokenRepository)
51
    {
52 11
        $this->accessTokenRepository = $accessTokenRepository;
53 11
    }
54
55
    /**
56
     * Set the public key
57
     *
58
     * @param CryptKey $key
59
     */
60 11
    public function setPublicKey(CryptKey $key)
61
    {
62 11
        $this->publicKey = $key;
63
64 11
        $this->initJwtConfiguration();
65 11
    }
66
67
    /**
68
     * Initialise the JWT configuration.
69
     */
70 11
    private function initJwtConfiguration()
71
    {
72 11
        $this->jwtConfiguration = Configuration::forSymmetricSigner(
73 11
            new Sha256(),
74 11
            InMemory::plainText('')
75
        );
76
77 11
        $this->jwtConfiguration->setValidationConstraints(
78 11
            new StrictValidAt(new SystemClock(new DateTimeZone(\date_default_timezone_get()))),
79 11
            new SignedWith(new Sha256(), LocalFileReference::file($this->publicKey->getKeyPath()))
80
        );
81 11
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 11
    public function validateAuthorization(ServerRequestInterface $request)
87
    {
88 11
        if ($request->hasHeader('authorization') === false) {
89 1
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
90
        }
91
92 10
        $header = $request->getHeader('authorization');
93 10
        $jwt = \trim((string) \preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
94
95
        try {
96
            // Attempt to parse the JWT
97 10
            $token = $this->jwtConfiguration->parser()->parse($jwt);
98 3
        } catch (\Lcobucci\JWT\Exception $exception) {
99 3
            throw OAuthServerException::accessDenied($exception->getMessage(), null, $exception);
100
        }
101
102
        try {
103
            // Attempt to validate the JWT
104 7
            $constraints = $this->jwtConfiguration->validationConstraints();
105 7
            $this->jwtConfiguration->validator()->assert($token, ...$constraints);
106 3
        } catch (RequiredConstraintsViolated $exception) {
107 3
            throw OAuthServerException::accessDenied('Access token could not be verified');
108
        }
109
110 4
        $claims = $token->claims();
111
112
        // Check if token has been revoked
113 4
        if ($this->accessTokenRepository->isAccessTokenRevoked($claims->get('jti'))) {
114 1
            throw OAuthServerException::accessDenied('Access token has been revoked');
115
        }
116
117
        // Return the request with additional attributes
118
        return $request
119 3
            ->withAttribute('oauth_access_token_id', $claims->get('jti'))
120 3
            ->withAttribute('oauth_client_id', $this->convertSingleRecordAudToString($claims->get('aud')))
121 3
            ->withAttribute('oauth_user_id', $claims->get('sub'))
122 3
            ->withAttribute('oauth_scopes', $claims->get('scopes'));
123
    }
124
125
    /**
126
     * Convert single record arrays into strings to ensure backwards compatibility between v4 and v3.x of lcobucci/jwt
127
     *
128
     * @param mixed $aud
129
     *
130
     * @return array|string
131
     */
132 3
    private function convertSingleRecordAudToString($aud)
133
    {
134 3
        return \is_array($aud) && \count($aud) === 1 ? $aud[0] : $aud;
135
    }
136
}
137