Completed
Push — master ( fec6f1...fc6f01 )
by Alexandre
03:31
created

AuthorizationRequestBuilder::build()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 15
nop 2
dl 0
loc 32
rs 8.7857
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Alexandre
5
 * Date: 11/06/2018
6
 * Time: 21:06
7
 */
8
9
namespace OAuth2\Extensions\PKCE\Endpoints\Authorization;
10
11
12
use OAuth2\Exceptions\InvalidAuthorizationRequest;
13
use OAuth2\Exceptions\InvalidRequestMethod;
14
use OAuth2\Exceptions\OAuthException;
15
use OAuth2\Roles\ClientTypes\PublicClient;
16
use OAuth2\Roles\ResourceOwnerInterface;
17
use Psr\Http\Message\ServerRequestInterface;
18
19
class AuthorizationRequestBuilder extends \OAuth2\Endpoints\Authorization\AuthorizationRequestBuilder
20
{
21
    /**
22
     * @param ServerRequestInterface $request
23
     * @param ResourceOwnerInterface $resourceOwner
24
     * @return AuthorizationRequest
25
     * @throws InvalidRequestMethod
26
     * @throws OAuthException
27
     * @throws InvalidAuthorizationRequest
28
     */
29
    public function build(ServerRequestInterface $request, ResourceOwnerInterface $resourceOwner): \OAuth2\Endpoints\Authorization\AuthorizationRequest
30
    {
31
        $authorizationRequest = parent::build($request, $resourceOwner);
32
33
        try {
34
            $codeChallenge = $authorizationRequest->getData()['code_challenge'] ?? null;
35
36
            $codeChallengeMethod = 'plain';
37
            if(!empty($authorizationRequest->getData()['code_challenge_method'])) {
38
                $codeChallengeMethod = $authorizationRequest->getData()['code_challenge_method'];
39
            }
40
41
            if (empty($codeChallenge)) {
42
                if ($authorizationRequest->getClient() instanceof PublicClient) {
43
                    throw new OAuthException('invalid_request',
44
                        'The request is missing the required parameter code_challenge for public clients.',
45
                        'https://tools.ietf.org/html/rfc7636#section-4.4');
46
                }
47
                return $authorizationRequest;
48
            }
49
50
            if (!in_array($codeChallengeMethod, ['plain', 'S256'])) {
51
                throw new OAuthException('invalid_request',
52
                    'The request includes the invalid parameter code_challenge_method. Supported : plain, S256.',
53
                    'https://tools.ietf.org/html/rfc7636#section-4');
54
            }
55
        } catch (OAuthException $e) {
56
            throw new InvalidAuthorizationRequest($e, $authorizationRequest->getRedirectUri(),
57
                $authorizationRequest->getResponseMode(), $authorizationRequest->getState());
58
        }
59
60
        return new AuthorizationRequest($authorizationRequest, $codeChallenge, $codeChallengeMethod);
61
    }
62
}