Completed
Pull Request — master (#736)
by
unknown
32:11
created

BearerTokenValidator::getAccessToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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