Completed
Pull Request — master (#1029)
by Andrew
01:51 queued 36s
created

BearerTokenValidator::setPublicKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

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