Completed
Push — master ( 289dee...aec877 )
by Alexandre
03:35
created

IdTokenResponseType   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 28
dl 0
loc 154
c 0
b 0
f 0
ccs 0
cts 33
cp 0
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A isQueryResponseModeSupported() 0 3 1
A isMultiValuedResponseTypeSupported() 0 3 1
A verifyRequest() 0 13 3
A getResponseType() 0 3 1
A requireTLS() 0 3 1
A isImplicit() 0 3 1
A __construct() 0 7 1
A getExtendedResponseTypes() 0 2 1
A getDefaultResponseMode() 0 3 1
C handle() 0 67 17
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: GCC-MED
5
 * Date: 19/01/2018
6
 * Time: 15:06
7
 */
8
9
namespace OAuth2\OpenID\ResponseTypes;
10
11
12
use Firebase\JWT\JWT;
13
use OAuth2\OpenID\Config;
14
use OAuth2\Exceptions\OAuthException;
15
use OAuth2\OpenID\Credentials\IdToken;
16
use OAuth2\OpenID\ResponseModes\ResponseModeInterface;
17
use OAuth2\OpenID\Storages\UserInfoClaimsStorage;
18
use OAuth2\Repositories\ConfigurationRepository;
19
use OAuth2\Roles\Clients\RegisteredClient;
20
use OAuth2\Roles\ResourceOwnerInterface;
21
use OAuth2\OpenID\Storages\IdTokenStorageInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
class IdTokenResponseType implements ResponseTypeInterface
25
{
26
    /**
27
     * @var ConfigurationRepository
28
     */
29
    private $configurationRepository;
30
    /**
31
     * @var IdTokenStorageInterface
32
     */
33
    private $idTokenStorage;
34
    /**
35
     * @var UserInfoClaimsStorage
36
     */
37
    private $userInfoClaimsStorage;
38
39
    public function __construct(ConfigurationRepository $configurationRepository,
40
                                IdTokenStorageInterface $idTokenStorage,
41
                                UserInfoClaimsStorage $userInfoClaimsStorage)
42
{
43
    $this->configurationRepository = $configurationRepository;
44
    $this->idTokenStorage = $idTokenStorage;
45
    $this->userInfoClaimsStorage = $userInfoClaimsStorage;
46
}
47
48
    public function getResponseType(): string
49
    {
50
        return 'id_token';
51
    }
52
53
    /**
54
     * @param ServerRequestInterface $request
55
     * @param ResourceOwnerInterface $resourceOwner
56
     * @param RegisteredClient $client
57
     * @param array|null $scope
58
     * @param array|null $extendedResponseTypes
59
     * @return array
60
     */
61
    public function handle(ServerRequestInterface $request, ResourceOwnerInterface $resourceOwner,
62
                           RegisteredClient $client, ?array $scope = null, ?array $extendedResponseTypes = null): array
63
    {
64
        $data = $request->getMethod() === 'GET' ? $request->getQueryParams() : $request->getParsedBody();
65
66
        // Get required claims
67
        $claims = [
68
            'iss' => $this->configurationRepository->getConfig(Config::OPENID_ISSUER),
69
            'sub' => $resourceOwner->getIdentifier(),
70
            'aud' => $client->getIdentifier(),
71
            'exp' => time() + $this->idTokenStorage->getLifetime(),
72
            'iat' => time()
73
        ];
74
75
        // todo, include if auth_time is marked as an essential claim by the client otherwise it is optional (conf ?)
76
        if(isset($data['max_age']) && $data['max_age']) {
77
            $claims['auth_time'] = $resourceOwner->getTimeWhenAuthenticationOccured();
78
        }
79
80
        if(isset($data['nonce']) && !is_null($data['nonce'])) {
81
            $claims['nonce'] = $data['nonce'];
82
        }
83
84
        if(empty($extendedResponseTypes)) {
85
            $standardClaims = $this->userInfoClaimsStorage->getClaims($resourceOwner);
86
87
            foreach ($this->userInfoClaimsStorage->getClaimsByScope($scope) as $claimRequested) {
88
                if(isset($standardClaims[$claimRequested]) && $standardClaims[$claimRequested]) {
89
                    $claims[$claimRequested] = $standardClaims[$claimRequested];
90
                }
91
            }
92
        }
93
94
        if(isset($extendedResponseTypes['code'])) {
95
            //c_hash
96
            /**
97
             * @var \OAuth2\ResponseTypes\ResponseTypeInterface $responseType
98
             */
99
            $responseType = $extendedResponseTypes['code'];
100
            $code = $responseType->handle($request, $resourceOwner, $client, $scope)['code'];
101
            $result['code'] = $code;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.
Loading history...
102
            $claims['c_hash'] = 'todo'; //todo
103
        }
104
105
        if(isset($extendedResponseTypes['token'])) {
106
            //at_hash
107
            /**
108
             * @var \OAuth2\ResponseTypes\ResponseTypeInterface $responseType
109
             */
110
            $responseType = $extendedResponseTypes['token'];
111
            $token = $responseType->handle($request, $resourceOwner, $client, $scope)['token'];
112
            $result['token'] = $token;
113
            $claims['at_hash'] = 'todo'; //todo
114
        }
115
        else {
116
            $requestedScopes = isset($data['scope']) ? explode(' ', $data['scope']) : [];
117
118
            if ((empty($requestedScopes) && !is_null($scope)) || (is_array($scope) && !empty(array_diff($requestedScopes, $scope)))) {
119
                $data['scope'] = implode(' ', $scope);
120
            }
121
        }
122
123
124
//        $idToken = new IdToken($claims);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
        $key = 'mykey'; // todo
126
        $result['id_token'] = JWT::encode($claims, $key);
127
        return $result;
128
    }
129
130
    public function getDefaultResponseMode(): string
131
    {
132
        return ResponseModeInterface::RESPONSE_MODE_FRAGMENT;
133
    }
134
135
    public function isImplicit(): bool
136
    {
137
        return true;
138
    }
139
140
    /**
141
     * @param ServerRequestInterface $request
142
     * @throws OAuthException
143
     */
144
    public function verifyRequest(ServerRequestInterface $request): void
145
    {
146
        $scope = explode(' ', $request->getQueryParams()['scope'] ?? $request->getParsedBody()['scope'] ?? null);
147
        if (is_null($scope)) {
0 ignored issues
show
introduced by
The condition is_null($scope) can never be true.
Loading history...
148
            throw new OAuthException('invalid_request',
149
                'Missing a required parameter : scope',
150
                'http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint'
151
            );
152
        }
153
        if (!in_array('openid', $scope)) {
154
            throw new OAuthException('invalid_request',
155
                'Invalid scope parameter : openid scope value must be present',
156
                'http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint'
157
            );
158
        }
159
    }
160
161
    public function requireTLS(): bool
162
    {
163
        return true;
164
    }
165
166
    public function isMultiValuedResponseTypeSupported(): bool
167
    {
168
        return true;
169
    }
170
171
    public function getExtendedResponseTypes(): ?array {
172
        return ['code', 'token'];
173
    }
174
175
    public function isQueryResponseModeSupported(): bool
176
    {
177
        return false;
178
    }
179
}