Completed
Pull Request — master (#897)
by
unknown
04:15 queued 17s
created

BearerTokenValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 Lcobucci\JWT\Parser;
13
use Lcobucci\JWT\Signer\Rsa\Sha256;
14
use Lcobucci\JWT\ValidationData;
15
use League\OAuth2\Server\CryptKey;
16
use League\OAuth2\Server\CryptTrait;
17
use League\OAuth2\Server\Exception\OAuthServerException;
18
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
21
class BearerTokenValidator implements AuthorizationValidatorInterface
22
{
23
    use CryptTrait;
24
25
    /**
26
     * @var AccessTokenRepositoryInterface
27
     */
28
    private $accessTokenRepository;
29
30
    /**
31
     * @var \League\OAuth2\Server\CryptKey
32
     */
33
    protected $publicKey;
34
35
    /**
36
     * @param AccessTokenRepositoryInterface $accessTokenRepository
37
     */
38 9
    public function __construct(AccessTokenRepositoryInterface $accessTokenRepository)
39
    {
40 9
        $this->accessTokenRepository = $accessTokenRepository;
41 9
    }
42
43
    /**
44
     * Set the public key
45
     *
46
     * @param \League\OAuth2\Server\CryptKey $key
47
     */
48 9
    public function setPublicKey(CryptKey $key)
49
    {
50 9
        $this->publicKey = $key;
51 9
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 9
    public function validateAuthorizationHeader(ServerRequestInterface $request)
57
    {
58 9
        if ($request->hasHeader('authorization') === false) {
59 1
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
60
        }
61
62 8
        $header = $request->getHeader('authorization');
63 8
        $jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
64
65
        try {
66
            // Attempt to parse and validate the JWT
67 8
            $token = (new Parser())->parse($jwt);
68 5
            if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
69 1
                throw OAuthServerException::accessDenied('Access token could not be verified');
70
            }
71
72
            // Ensure access token hasn't expired
73 4
            $data = new ValidationData();
74 4
            $data->setCurrentTime(time());
75
76 4
            if ($token->validate($data) === false) {
77 1
                throw OAuthServerException::accessDenied('Access token is invalid');
78
            }
79
80
            // Check if token has been revoked
81 3
            if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
82 1
                throw OAuthServerException::accessDenied('Access token has been revoked');
83
            }
84
85
            // Return the token
86 2
            return $token;
87 6
        } catch (\InvalidArgumentException $exception) {
88
            // JWT couldn't be parsed so return the request as is
89 2
            throw OAuthServerException::accessDenied($exception->getMessage());
90 4
        } catch (\RuntimeException $exception) {
91
            //JWR couldn't be parsed so return the request as is
92 1
            throw OAuthServerException::accessDenied('Error while decoding to JSON');
93
        }
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 9
    public function validateAuthorization(ServerRequestInterface $request)
100
    {
101 9
        $token = $this->validateAuthorizationHeader($request);
102
103
        return $request
104 2
            ->withAttribute('oauth_access_token_id', $token->getClaim('jti'))
105 2
            ->withAttribute('oauth_client_id', $token->getClaim('aud'))
106 2
            ->withAttribute('oauth_user_id', $token->getClaim('sub'))
107 2
            ->withAttribute('oauth_scopes', $token->getClaim('scopes'));
108
    }
109
}
110