Completed
Push — master ( 06424f...aac467 )
by Alex
86:38 queued 51:34
created

BearerTokenValidator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 9
c 0
b 0
f 0
lcom 1
cbo 9
dl 0
loc 79
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setPublicKey() 0 4 1
C validateAuthorization() 0 43 7
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
    public function __construct(AccessTokenRepositoryInterface $accessTokenRepository)
39
    {
40
        $this->accessTokenRepository = $accessTokenRepository;
41
    }
42
43
    /**
44
     * Set the private key
45
     *
46
     * @param \League\OAuth2\Server\CryptKey $key
47
     */
48
    public function setPublicKey(CryptKey $key)
49
    {
50
        $this->publicKey = $key;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function validateAuthorization(ServerRequestInterface $request)
57
    {
58
        if ($request->hasHeader('authorization') === false) {
59
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
60
        }
61
62
        $header = $request->getHeader('authorization');
63
        $jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
64
65
        try {
66
            // Attempt to parse and validate the JWT
67
            $token = (new Parser())->parse($jwt);
68
            if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
69
                throw OAuthServerException::accessDenied('Access token could not be verified');
70
            }
71
72
            // Ensure access token hasn't expired
73
            $data = new ValidationData();
74
            $data->setCurrentTime(time());
75
76
            if ($token->validate($data) === false) {
77
                throw OAuthServerException::accessDenied('Access token is invalid');
78
            }
79
80
            // Check if token has been revoked
81
            if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
82
                throw OAuthServerException::accessDenied('Access token has been revoked');
83
            }
84
85
            // Return the request with additional attributes
86
            return $request
87
                ->withAttribute('oauth_access_token_id', $token->getClaim('jti'))
88
                ->withAttribute('oauth_client_id', $token->getClaim('aud'))
89
                ->withAttribute('oauth_user_id', $token->getClaim('sub'))
90
                ->withAttribute('oauth_scopes', $token->getClaim('scopes'));
91
        } catch (\InvalidArgumentException $exception) {
92
            // JWT couldn't be parsed so return the request as is
93
            throw OAuthServerException::accessDenied($exception->getMessage());
94
        } catch (\RuntimeException $exception) {
95
            //JWR couldn't be parsed so return the request as is
96
            throw OAuthServerException::accessDenied('Error while decoding to JSON');
97
        }
98
    }
99
}
100