Completed
Pull Request — master (#7)
by
unknown
02:02
created

Keycloak::checkResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Stevenmaguire\OAuth2\Client\Provider;
4
5
use Exception;
6
use Firebase\JWT\JWT;
7
use League\OAuth2\Client\Provider\AbstractProvider;
8
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
9
use League\OAuth2\Client\Token\AccessToken;
10
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
11
use Psr\Http\Message\ResponseInterface;
12
use Stevenmaguire\OAuth2\Client\Provider\Exception\EncryptionConfigurationException;
13
14
class Keycloak extends AbstractProvider
15
{
16
    use BearerAuthorizationTrait;
17
18
    /**
19
     * Keycloak URL, eg. http://localhost:8080/auth.
20
     *
21
     * @var string
22
     */
23
    public $authServerUrl = null;
24
25
    /**
26
     * Realm name, eg. demo.
27
     *
28
     * @var string
29
     */
30
    public $realm = null;
31
32
    /**
33
     * Encryption algorithm.
34
     *
35
     * You must specify supported algorithms for your application. See
36
     * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
37
     * for a list of spec-compliant algorithms.
38
     *
39
     * @var string
40
     */
41
    public $encryptionAlgorithm = null;
42
43
    /**
44
     * Encryption key.
45
     *
46
     * @var string
47
     */
48
    public $encryptionKey = null;
49
    /**
50
     * Access Token once authenticated.
51
     *
52
     * @var AccessToken
53
     */
54
    protected $accessToken = null;
55
56
    /**
57
     * @var KeyCloakRoles Any roles obtained from the access token.
58
     */
59
    private $keycloakRoles = null;
60
    /**
61
     * @var KeycloakEntitlements
62
     */
63
    private $keycloakEntitlements = null;
64
65
    /**
66
     * Constructs an OAuth 2.0 service provider.
67
     *
68
     * @param array $options An array of options to set on this provider.
69
     *     Options include `clientId`, `clientSecret`, `redirectUri`, and `state`.
70
     *     Individual providers may introduce more options, as needed.
71
     * @param array $collaborators An array of collaborators that may be used to
72
     *     override this provider's default behavior. Collaborators include
73
     *     `grantFactory`, `requestFactory`, `httpClient`, and `randomFactory`.
74
     *     Individual providers may introduce more collaborators, as needed.
75
     */
76 34
    public function __construct(array $options = [], array $collaborators = [])
77
    {
78 34
        if (isset($options['encryptionKeyPath'])) {
79 2
            $this->setEncryptionKeyPath($options['encryptionKeyPath']);
80 2
            unset($options['encryptionKeyPath']);
81 1
        }
82 34
        parent::__construct($options, $collaborators);
83 34
    }
84
85
    /**
86
     * We need to cache the access token locally allowing for later optional post-processing
87
     * by `checkForKeycloakRoles()`
88
     *
89
     * @param mixed $grant
90
     * @param array $options
91
     * @return AccessToken
92
     */
93 10
    public function getAccessToken($grant, array $options = [])
94
    {
95 10
        $this->accessToken = parent::getAccessToken($grant, $options);
96 8
        return $this->accessToken;
97
    }
98
99
    /**
100
     * Check for Keycloak-supplied additional fields held by the access token which in turn is inside accessToken.
101
     *
102
     * @return KeyCloakRoles
103
     */
104 1
    public function getKeycloakRoles()
105
    {
106
        if ($this->accessToken != null && $this->encryptionKey != null && $this->encryptionAlgorithm != null) {
107
            $obj = JWT::decode($this->accessToken, $this->encryptionKey, array($this->encryptionAlgorithm));
108
            $this->keycloakRoles = new KeycloakRoles($obj);
109
        }
110
        return $this->keycloakRoles;
111 1
    }
112
113
    /**
114
     * Obtain the Keycloak entitlements (permissions) this authenticated user has for this resource (by client-id).
115
     *
116
     * This uses the Entitlement API offered by Keycloak.
117
     * @return KeycloakEntitlements Entitlements in a convenient wrapper model
118
     */
119 1
    public function getKeycloakEntitlements()
120
    {
121
        if ($this->keycloakEntitlements == null) {
122
            $request = $this->getAuthenticatedRequest(
123 1
                'GET',
124
                $this->getEntitlementsUrl($this->accessToken),
125
                $this->accessToken,
126
                []
127
            );
128
            $response = $this->getParsedResponse($request);
129
            // Should have an rpt field
130
            $entitlements = JWT::decode(
131
                $response['rpt'],
132
                $this->encryptionKey,
133
                [$this->encryptionAlgorithm]
134
            );
135
            $this->keycloakEntitlements = new KeycloakEntitlements($entitlements);
136
        }
137
138
        return $this->keycloakEntitlements;
139
    }
140
141
    /**
142
     * Attempts to decrypt the given response.
143
     *
144
     * @param  string|array|null $response
145
     * @return array|null|string
146
     * @throws EncryptionConfigurationException
147
     */
148 6
    public function decryptResponse($response)
149
    {
150 6
        if (is_string($response)) {
151 4
            if ($this->encryptionAlgorithm && $this->encryptionKey) {
152 2
                $response = json_decode(
153 2
                    json_encode(
154 2
                        JWT::decode(
155 2
                            $response,
156 2
                            $this->encryptionKey,
157 2
                            array($this->encryptionAlgorithm)
158 1
                        )
159 1
                    ),
160 1
                    true
161 1
                );
162 1
            } else {
163 2
                throw new EncryptionConfigurationException(
164
                    'The given response may be encrypted and sufficient ' .
165 2
                    'encryption configuration has not been provided.',
166 1
                    400
167 1
                );
168
            }
169 1
        }
170
171 4
        return $response;
172
    }
173
174
    /**
175
     * Get authorization url to begin OAuth flow
176
     *
177
     * @return string
178
     */
179 6
    public function getBaseAuthorizationUrl()
180
    {
181 6
        return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/auth';
182
    }
183
184
    /**
185
     * Get access token url to retrieve token
186
     *
187
     * @param  array $params
188
     *
189
     * @return string
190
     */
191 12
    public function getBaseAccessTokenUrl(array $params)
192
    {
193 12
        return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/token';
194
    }
195
196
    /**
197
     * Get provider url to fetch user details
198
     *
199
     * @param  AccessToken $token
200
     *
201
     * @return string
202
     */
203 6
    public function getResourceOwnerDetailsUrl(AccessToken $token)
204
    {
205 6
        return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/userinfo';
206
    }
207
208
    /**
209
     * Keycloak extension supporting entitlements.
210
     *
211
     * @param AccessToken $token
212
     * @return string
213
     */
214
    public function getEntitlementsUrl(AccessToken $token)
0 ignored issues
show
Unused Code introduced by
The parameter $token is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
215
    {
216
        return $this->getBaseUrlWithRealm() . '/authz/entitlement/' . $this->clientId;
217
    }
218
219
    /**
220
     * Creates base url from provider configuration.
221
     *
222
     * @return string
223
     */
224 18
    protected function getBaseUrlWithRealm()
225
    {
226 18
        return $this->authServerUrl . '/realms/' . $this->realm;
227
    }
228
229
    /**
230
     * Get the default scopes used by this provider.
231
     *
232
     * This should not be a complete list of all scopes, but the minimum
233
     * required for the provider user interface!
234
     *
235
     * @return string[]
236
     */
237 4
    protected function getDefaultScopes()
238
    {
239 4
        return ['name', 'email'];
240
    }
241
242 6
    protected function getAuthorizationHeaders($token = null)
243
    {
244 6
        $headers = parent::getAuthorizationHeaders($token);
245 6
        if ($token != null) {
246 6
            $headers['Authorization'] = 'Bearer ' . $token;
247 3
        }
248 6
        return $headers;
249
    }
250
251
    /**
252
     * Check a provider response for errors.
253
     *
254
     * @throws IdentityProviderException
255
     * @param  ResponseInterface $response
256
     * @param  string $data Parsed response data
257
     * @return void
258
     */
259 10
    protected function checkResponse(ResponseInterface $response, $data)
260
    {
261 10
        if (!empty($data['error'])) {
262 2
            $error = $data['error'] . ': ' . $data['error_description'];
263 2
            throw new IdentityProviderException($error, 0, $data);
264
        }
265 8
    }
266
267
    /**
268
     * Generate a user object from a successful user details request.
269
     *
270
     * @param array $response
271
     * @param AccessToken $token
272
     * @return KeycloakResourceOwner
273
     */
274 4
    protected function createResourceOwner(array $response, AccessToken $token)
275
    {
276 4
        return new KeycloakResourceOwner($response);
277
    }
278
279
    /**
280
     * Requests and returns the resource owner of given access token.
281
     *
282
     * @param  AccessToken $token
283
     * @return KeycloakResourceOwner
284
     */
285 6
    public function getResourceOwner(AccessToken $token)
286
    {
287 6
        $response = $this->fetchResourceOwnerDetails($token);
288
289 6
        $response = $this->decryptResponse($response);
290
291 4
        return $this->createResourceOwner($response, $token);
0 ignored issues
show
Bug introduced by
It seems like $response defined by $this->decryptResponse($response) on line 289 can also be of type null or string; however, Stevenmaguire\OAuth2\Cli...::createResourceOwner() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
292
    }
293
294
    /**
295
     * Updates expected encryption algorithm of Keycloak instance.
296
     *
297
     * @param string $encryptionAlgorithm
298
     *
299
     * @return Keycloak
300
     */
301 4
    public function setEncryptionAlgorithm($encryptionAlgorithm)
302
    {
303 4
        $this->encryptionAlgorithm = $encryptionAlgorithm;
304
305 4
        return $this;
306
    }
307
308
    /**
309
     * Updates expected encryption key of Keycloak instance.
310
     *
311
     * @param string $encryptionKey
312
     *
313
     * @return Keycloak
314
     */
315 4
    public function setEncryptionKey($encryptionKey)
316
    {
317 4
        $this->encryptionKey = $encryptionKey;
318
319 4
        return $this;
320
    }
321
322
    /**
323
     * Updates expected encryption key of Keycloak instance to content of given
324
     * file path.
325
     *
326
     * @param string $encryptionKeyPath
327
     *
328
     * @return Keycloak
329
     */
330 2
    public function setEncryptionKeyPath($encryptionKeyPath)
331
    {
332
        try {
333 2
            $this->encryptionKey = file_get_contents($encryptionKeyPath);
334 1
        } catch (Exception $e) {
335
            // Not sure how to handle this yet.
336
        }
337
338 2
        return $this;
339
    }
340
}
341