Completed
Push — master ( 523434...f5c3ba )
by Alex
145:03 queued 109:43
created

AuthCodeGrant::getIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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\Grant;
11
12
use League\OAuth2\Server\Entities\ClientEntityInterface;
13
use League\OAuth2\Server\Entities\ScopeEntityInterface;
14
use League\OAuth2\Server\Entities\UserEntityInterface;
15
use League\OAuth2\Server\Exception\OAuthServerException;
16
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
17
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
18
use League\OAuth2\Server\RequestEvent;
19
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
20
use League\OAuth2\Server\ResponseTypes\RedirectResponse;
21
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
class AuthCodeGrant extends AbstractAuthorizeGrant
25
{
26
    /**
27
     * @var \DateInterval
28
     */
29
    private $authCodeTTL;
30
31
    /**
32
     * @var bool
33
     */
34
    private $enableCodeExchangeProof = false;
35
36
    /**
37
     * @param AuthCodeRepositoryInterface     $authCodeRepository
38
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
39
     * @param \DateInterval                   $authCodeTTL
40
     */
41
    public function __construct(
42
        AuthCodeRepositoryInterface $authCodeRepository,
43
        RefreshTokenRepositoryInterface $refreshTokenRepository,
44
        \DateInterval $authCodeTTL
45
    ) {
46
        $this->setAuthCodeRepository($authCodeRepository);
47
        $this->setRefreshTokenRepository($refreshTokenRepository);
48
        $this->authCodeTTL = $authCodeTTL;
49
        $this->refreshTokenTTL = new \DateInterval('P1M');
50
    }
51
52
    public function enableCodeExchangeProof()
53
    {
54
        $this->enableCodeExchangeProof = true;
55
    }
56
57
    /**
58
     * Respond to an access token request.
59
     *
60
     * @param ServerRequestInterface $request
61
     * @param ResponseTypeInterface  $responseType
62
     * @param \DateInterval          $accessTokenTTL
63
     *
64
     * @throws OAuthServerException
65
     *
66
     * @return ResponseTypeInterface
67
     */
68
    public function respondToAccessTokenRequest(
69
        ServerRequestInterface $request,
70
        ResponseTypeInterface $responseType,
71
        \DateInterval $accessTokenTTL
72
    ) {
73
        // Validate request
74
        $client = $this->validateClient($request);
75
        $encryptedAuthCode = $this->getRequestParameter('code', $request, null);
76
77
        if ($encryptedAuthCode === null) {
78
            throw OAuthServerException::invalidRequest('code');
79
        }
80
81
        // Validate the authorization code
82
        try {
83
            $authCodePayload = json_decode($this->decrypt($encryptedAuthCode));
84
            if (time() > $authCodePayload->expire_time) {
85
                throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
86
            }
87
88
            if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
89
                throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
90
            }
91
92
            if ($authCodePayload->client_id !== $client->getIdentifier()) {
93
                throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
94
            }
95
96
            // The redirect URI is required in this request
97
            $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
98
            if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
99
                throw OAuthServerException::invalidRequest('redirect_uri');
100
            }
101
102
            if ($authCodePayload->redirect_uri !== $redirectUri) {
103
                throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
104
            }
105
106
            $scopes = [];
107
            foreach ($authCodePayload->scopes as $scopeId) {
108
                $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeId);
109
110
                if ($scope instanceof ScopeEntityInterface === false) {
111
                    // @codeCoverageIgnoreStart
112
                    throw OAuthServerException::invalidScope($scopeId);
113
                    // @codeCoverageIgnoreEnd
114
                }
115
116
                $scopes[] = $scope;
117
            }
118
119
            // Finalize the requested scopes
120
            $scopes = $this->scopeRepository->finalizeScopes(
121
                $scopes,
122
                $this->getIdentifier(),
123
                $client,
124
                $authCodePayload->user_id
125
            );
126
        } catch (\LogicException  $e) {
127
            throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code');
128
        }
129
130
        // Validate code challenge
131
        if ($this->enableCodeExchangeProof === true) {
132
            $codeVerifier = $this->getRequestParameter('code_verifier', $request, null);
133
            if ($codeVerifier === null) {
134
                throw OAuthServerException::invalidRequest('code_verifier');
135
            }
136
137
            switch ($authCodePayload->code_challenge_method) {
138
                case 'plain':
139
                    if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
140
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
141
                    }
142
143
                    break;
144
                case 'S256':
145
                    if (
146
                        hash_equals(
147
                            urlencode(base64_encode(hash('sha256', $codeVerifier))),
148
                            $authCodePayload->code_challenge
149
                        ) === false
150
                    ) {
151
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
152
                    }
153
                    // @codeCoverageIgnoreStart
154
                    break;
155
                default:
156
                    throw OAuthServerException::serverError(
157
                        sprintf(
158
                            'Unsupported code challenge method `%s`',
159
                            $authCodePayload->code_challenge_method
160
                        )
161
                    );
162
                // @codeCoverageIgnoreEnd
163
            }
164
        }
165
166
        // Issue and persist access + refresh tokens
167
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
168
        $refreshToken = $this->issueRefreshToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...load->user_id, $scopes) on line 167 can be null; however, League\OAuth2\Server\Gra...nt::issueRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
169
170
        // Inject tokens into response type
171
        $responseType->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...load->user_id, $scopes) on line 167 can be null; however, League\OAuth2\Server\Res...rface::setAccessToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
172
        $responseType->setRefreshToken($refreshToken);
0 ignored issues
show
Bug introduced by
It seems like $refreshToken defined by $this->issueRefreshToken($accessToken) on line 168 can be null; however, League\OAuth2\Server\Res...face::setRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
173
174
        // Revoke used auth code
175
        $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);
176
177
        return $responseType;
178
    }
179
180
    /**
181
     * Return the grant identifier that can be used in matching up requests.
182
     *
183
     * @return string
184
     */
185
    public function getIdentifier()
186
    {
187
        return 'authorization_code';
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
194
    {
195
        return (
196
            array_key_exists('response_type', $request->getQueryParams())
197
            && $request->getQueryParams()['response_type'] === 'code'
198
            && isset($request->getQueryParams()['client_id'])
199
        );
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205
    public function validateAuthorizationRequest(ServerRequestInterface $request)
206
    {
207
        $clientId = $this->getQueryStringParameter(
208
            'client_id',
209
            $request,
210
            $this->getServerParameter('PHP_AUTH_USER', $request)
211
        );
212
        if (is_null($clientId)) {
213
            throw OAuthServerException::invalidRequest('client_id');
214
        }
215
216
        $client = $this->clientRepository->getClientEntity(
217
            $clientId,
218
            $this->getIdentifier(),
219
            null,
220
            false
221
        );
222
223
        if ($client instanceof ClientEntityInterface === false) {
224
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
225
            throw OAuthServerException::invalidClient();
226
        }
227
228
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
229
        if ($redirectUri !== null) {
230
            if (
231
                is_string($client->getRedirectUri())
232
                && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
233
            ) {
234
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
235
                throw OAuthServerException::invalidClient();
236
            } elseif (
237
                is_array($client->getRedirectUri())
238
                && in_array($redirectUri, $client->getRedirectUri()) === false
239
            ) {
240
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
241
                throw OAuthServerException::invalidClient();
242
            }
243
        }
244
245
        $scopes = $this->validateScopes(
246
            $this->getQueryStringParameter('scope', $request),
247
            is_array($client->getRedirectUri())
248
                ? $client->getRedirectUri()[0]
249
                : $client->getRedirectUri()
250
        );
251
252
        $stateParameter = $this->getQueryStringParameter('state', $request);
253
254
        $authorizationRequest = new AuthorizationRequest();
255
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
256
        $authorizationRequest->setClient($client);
257
        $authorizationRequest->setRedirectUri($redirectUri);
258
        $authorizationRequest->setState($stateParameter);
259
        $authorizationRequest->setScopes($scopes);
260
261
        if ($this->enableCodeExchangeProof === true) {
262
            $codeChallenge = $this->getQueryStringParameter('code_challenge', $request);
263
            if ($codeChallenge === null) {
264
                throw OAuthServerException::invalidRequest('code_challenge');
265
            }
266
267
            if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
268
                throw OAuthServerException::invalidRequest(
269
                    'code_challenge',
270
                    'The code_challenge must be between 43 and 128 characters'
271
                );
272
            }
273
274
            $codeChallengeMethod = $this->getQueryStringParameter('code_challenge_method', $request, 'plain');
275
            if (in_array($codeChallengeMethod, ['plain', 'S256']) === false) {
276
                throw OAuthServerException::invalidRequest(
277
                    'code_challenge_method',
278
                    'Code challenge method must be `plain` or `S256`'
279
                );
280
            }
281
282
            $authorizationRequest->setCodeChallenge($codeChallenge);
283
            $authorizationRequest->setCodeChallengeMethod($codeChallengeMethod);
284
        }
285
286
        return $authorizationRequest;
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
293
    {
294
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
295
            throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
296
        }
297
298
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
299
            ? is_array($authorizationRequest->getClient()->getRedirectUri())
300
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
301
                : $authorizationRequest->getClient()->getRedirectUri()
302
            : $authorizationRequest->getRedirectUri();
303
304
        // The user approved the client, redirect them back with an auth code
305
        if ($authorizationRequest->isAuthorizationApproved() === true) {
306
            $authCode = $this->issueAuthCode(
307
                $this->authCodeTTL,
308
                $authorizationRequest->getClient(),
309
                $authorizationRequest->getUser()->getIdentifier(),
310
                $authorizationRequest->getRedirectUri(),
311
                $authorizationRequest->getScopes()
312
            );
313
314
            $payload = [
315
                'client_id'               => $authCode->getClient()->getIdentifier(),
316
                'redirect_uri'            => $authCode->getRedirectUri(),
317
                'auth_code_id'            => $authCode->getIdentifier(),
318
                'scopes'                  => $authCode->getScopes(),
319
                'user_id'                 => $authCode->getUserIdentifier(),
320
                'expire_time'             => (new \DateTime())->add($this->authCodeTTL)->format('U'),
321
                'code_challenge'          => $authorizationRequest->getCodeChallenge(),
322
                'code_challenge_method  ' => $authorizationRequest->getCodeChallengeMethod(),
323
            ];
324
325
            $response = new RedirectResponse();
326
            $response->setRedirectUri(
327
                $this->makeRedirectUri(
328
                    $finalRedirectUri,
329
                    [
330
                        'code'  => $this->encrypt(
331
                            json_encode(
332
                                $payload
333
                            )
334
                        ),
335
                        'state' => $authorizationRequest->getState(),
336
                    ]
337
                )
338
            );
339
340
            return $response;
341
        }
342
343
        // The user denied the client, redirect them back with an error
344
        throw OAuthServerException::accessDenied(
345
            'The user denied the request',
346
            $this->makeRedirectUri(
347
                $finalRedirectUri,
348
                [
349
                    'state' => $authorizationRequest->getState(),
350
                ]
351
            )
352
        );
353
    }
354
}
355