Completed
Pull Request — master (#736)
by
unknown
35:10
created

BearerTokenValidator::setPublicKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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
    protected $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
     * @param ServerRequestInterface $request
55
     */
56
    public function getAccessToken(ServerRequestInterface $request) {
57
	    if ($request->hasHeader('authorization') === false) {
58
            throw OAuthServerException::accessDenied('Missing "Authorization" header');
59
        }
60
61
        $header = $request->getHeader('authorization');
62
        return trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function validateAuthorization(ServerRequestInterface $request)
69
    {
70
      	$jwt = $this->getAccessToken($request);
71
        try {
72
            // Attempt to parse and validate the JWT
73
            $token = (new Parser())->parse($jwt);
74
            if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
75
                throw OAuthServerException::accessDenied('Access token could not be verified');
76
            }
77
78
            // Ensure access token hasn't expired
79
            $data = new ValidationData();
80
            $data->setCurrentTime(time());
81
82
            if ($token->validate($data) === false) {
83
                throw OAuthServerException::accessDenied('Access token is invalid');
84
            }
85
86
            // Check if token has been revoked
87
            if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
88
                throw OAuthServerException::accessDenied('Access token has been revoked');
89
            }
90
91
            // Return the request with additional attributes
92
            return $request
93
                ->withAttribute('oauth_access_token_id', $token->getClaim('jti'))
94
                ->withAttribute('oauth_client_id', $token->getClaim('aud'))
95
                ->withAttribute('oauth_user_id', $token->getClaim('sub'))
96
                ->withAttribute('oauth_scopes', $token->getClaim('scopes'));
97
        } catch (\InvalidArgumentException $exception) {
98
            // JWT couldn't be parsed so return the request as is
99
            throw OAuthServerException::accessDenied($exception->getMessage());
100
        } catch (\RuntimeException $exception) {
101
            //JWR couldn't be parsed so return the request as is
102
            throw OAuthServerException::accessDenied('Error while decoding to JSON');
103
        }
104
    }
105
}
106