Passed
Push — master ( e88490...575397 )
by Alexandre
04:15
created

AuthorizationCodeFlow::base64url_encode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Alexandre
5
 * Date: 07/03/2018
6
 * Time: 23:43
7
 */
8
9
namespace OAuth2\Extensions\PKCE\Flows;
10
11
12
use OAuth2\Endpoints\AuthorizationEndpoint;
13
use OAuth2\Endpoints\TokenEndpoint;
14
use OAuth2\Exceptions\OAuthException;
15
use OAuth2\Extensions\PKCE\Credentials\CodeChallenge;
16
use OAuth2\Extensions\PKCE\Storages\AuthorizationCodeStorageInterface;
17
use OAuth2\Helper;
18
use OAuth2\Roles\Clients\PublicClient;
19
use OAuth2\Storages\AccessTokenStorageInterface;
20
use OAuth2\Storages\RefreshTokenStorageInterface;
21
22
/**
23
 * Class AuthorizationCodeFlow
24
 * @package OAuth2\Extensions\PKCE\Flows
25
 * @rfc https://tools.ietf.org/html/rfc7636
26
 */
27
class AuthorizationCodeFlow extends \OAuth2\Flows\AuthorizationCodeFlow
28
{
29
    /**
30
     * @var AuthorizationCodeStorageInterface
31
     */
32
    protected $authorizationCodeStorage;
33
34
    /**
35
     * AuthorizationCodeFlow constructor.
36
     * @param \OAuth2\Flows\AuthorizationCodeFlow $authorizationCodeFlow
37
     * @param AuthorizationCodeStorageInterface   $authorizationCodeStorage
38
     * @param AccessTokenStorageInterface         $accessTokenStorage
39
     * @param RefreshTokenStorageInterface        $refreshTokenStorage
40
     */
41
    public function __construct(\OAuth2\Flows\AuthorizationCodeFlow $authorizationCodeFlow,
42
                                AuthorizationCodeStorageInterface $authorizationCodeStorage,
43
                                AccessTokenStorageInterface $accessTokenStorage,
44
                                RefreshTokenStorageInterface $refreshTokenStorage)
45
    {
46
        parent::__construct($authorizationCodeStorage, $accessTokenStorage, $refreshTokenStorage);
47
        $this->authorizationCodeStorage = $authorizationCodeStorage;
48
    }
49
50
    /**
51
     * @param AuthorizationEndpoint $authorizationEndpoint
52
     * @param array                 $requestData
53
     * @return array
54
     * @throws OAuthException
55
     */
56
    function handleAuthorizationRequest(AuthorizationEndpoint $authorizationEndpoint, array $requestData): array
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
57
    {
58
        $authorizationCode = $this->createAuthorizationCode($authorizationEndpoint);
0 ignored issues
show
Bug introduced by
The method createAuthorizationCode() does not exist on OAuth2\Extensions\PKCE\Flows\AuthorizationCodeFlow. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

58
        /** @scrutinizer ignore-call */ 
59
        $authorizationCode = $this->createAuthorizationCode($authorizationEndpoint);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
59
60
        if (empty($requestData['code_challenge'])) {
61
            if ($authorizationEndpoint->getClient() instanceof PublicClient) {
62
                throw new OAuthException('invalid_request',
63
                    'The request is missing the required parameter code_challenge for public clients.',
64
                    'https://tools.ietf.org/html/rfc7636#section-4.4');
65
            }
66
        } else {
67
            $codeChallengeMethod = empty($requestData['code_challenge_method']) ? 'plain' : $requestData['code_challenge_method'];
68
            if (!in_array($codeChallengeMethod, ['plain', 'S256'])) {
69
                throw new OAuthException('invalid_request',
70
                    'The request includes the invalid parameter code_challenge_method. Supported : plain, S256.',
71
                    'https://tools.ietf.org/html/rfc7636#section-4');
72
            }
73
74
            $codeChallenge = new CodeChallenge($requestData['code_challenge'], $codeChallengeMethod);
75
            $this->authorizationCodeStorage->associate($codeChallenge, $authorizationCode);
76
        }
77
78
        return $this->saveAndGetResult($authorizationCode);
0 ignored issues
show
Bug introduced by
The method saveAndGetResult() does not exist on OAuth2\Extensions\PKCE\Flows\AuthorizationCodeFlow. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

78
        return $this->/** @scrutinizer ignore-call */ saveAndGetResult($authorizationCode);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
79
    }
80
81
    /**
82
     * @param TokenEndpoint $tokenEndpoint
83
     * @param array $requestData
84
     * @return array
85
     * @throws OAuthException
86
     */
87
    public function handleAccessTokenRequest(TokenEndpoint $tokenEndpoint, array $requestData): array
88
    {
89
        if (empty($requestData['code'])) {
90
            throw new OAuthException('invalid_request',
91
                'The request is missing the required parameter code.',
92
                'https://tools.ietf.org/html/rfc7636#section-4.4');
93
        }
94
        $code = $requestData['code'];
95
96
        $authorizationCode = $this->authorizationCodeStorage->find($code);
97
98
        /**
99
         * ensure that the authorization code was issued to the authenticated
100
         * confidential client, or if the client is public, ensure that the
101
         * code was issued to "client_id" in the request,
102
         */
103
        if (!$authorizationCode || $authorizationCode->getClientIdentifier() !== $tokenEndpoint->getClient()->getIdentifier()) {
104
            throw new OAuthException('invalid_grant',
105
                'The request includes the invalid parameter code.',
106
                'https://tools.ietf.org/html/rfc7636#section-4.4');
107
        }
108
109
        $this->authorizationCodeStorage->revoke($code);
110
111
        /**
112
         * verify that the authorization code is valid
113
         */
114
        if ($authorizationCode->isExpired()) {
0 ignored issues
show
Bug introduced by
The method isExpired() does not exist on OAuth2\Credentials\AuthorizationCodeInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

114
        if ($authorizationCode->/** @scrutinizer ignore-call */ isExpired()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
            throw new OAuthException('invalid_grant',
116
                'The request includes the invalid parameter code. The code has expired.',
117
                'https://tools.ietf.org/html/rfc7636#section-4.4');
118
        }
119
120
        /**
121
         * ensure that the "redirect_uri" parameter is present if the
122
         * "redirect_uri" parameter was included in the initial authorization
123
         * request as described in Section 4.1.1, and if included ensure that
124
         * their values are identical.
125
         */
126
        if ($authorizationCode->getRedirectUri()) {
127
            if (empty($requestData['redirect_uri'])) {
128
                throw new OAuthException('invalid_request',
129
                    'The request is missing the required parameter redirect_uri',
130
                    'https://tools.ietf.org/html/rfc7636#section-4.1');
131
            }
132
            if ($requestData['redirect_uri'] !== $authorizationCode->getRedirectUri()) {
133
                throw new OAuthException('invalid_request',
134
                    'The request includes the invalid parameter redirect_uri',
135
                    'https://tools.ietf.org/html/rfc7636#section-4.1');
136
            }
137
        }
138
139
        $codeChallenge = $this->authorizationCodeStorage->getCodeChallenge($authorizationCode);
140
141
        if ($codeChallenge && $codeChallenge->getCodeChallenge()) {
142
            if (empty($requestData['code_verifier'])) {
143
                throw new OAuthException('invalid_request',
144
                    'The request is missing the required parameter code_verifier',
145
                    'https://tools.ietf.org/html/rfc7636#section-4.4');
146
            }
147
148
            if ($codeChallenge->getCodeChallengeMethod() === 'S256') {
149
                /**
150
                 * If the "code_challenge_method" from Section 4.3 was "S256", the
151
                 * received "code_verifier" is hashed by SHA-256, base64url-encoded, and
152
                 * then compared to the "code_challenge", i.e.:
153
                 */
154
                $hashedCodeVerifier = Helper::base64url_encode(hash('sha256', $requestData['code_verifier']));
155
            } else {
156
                /**
157
                 * If the "code_challenge_method" from Section 4.3 was "plain", they are
158
                 * compared directly, i.e.:
159
                 */
160
                $hashedCodeVerifier = $requestData['code_verifier'];
161
            }
162
163
            /**
164
             * If the values are equal, the token endpoint MUST continue processing
165
             * as normal (as defined by OAuth 2.0 [RFC6749]).  If the values are not
166
             * equal, an error response indicating "invalid_grant" as described in
167
             * Section 5.2 of [RFC6749] MUST be returned.
168
             */
169
            if ($hashedCodeVerifier !== $codeChallenge->getCodeChallenge()) {
170
                throw new OAuthException('invalid_grant',
171
                    'The request includes the invalid parameter code_verifier',
172
                    'https://tools.ietf.org/html/rfc7636#section-4.4');
173
            }
174
        }
175
176
        return $this->issueTokens($authorizationCode->getScope(),
177
            $authorizationCode->getResourceOwnerIdentifier(), $authorizationCode->getCode());
178
    }
179
180
}