Completed
Push — master ( 86efb9...ab916e )
by Steven
02:46
created

Keycloak::setEncryptionKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
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
    /**
51
     * Constructs an OAuth 2.0 service provider.
52
     *
53
     * @param array $options An array of options to set on this provider.
54
     *     Options include `clientId`, `clientSecret`, `redirectUri`, and `state`.
55
     *     Individual providers may introduce more options, as needed.
56
     * @param array $collaborators An array of collaborators that may be used to
57
     *     override this provider's default behavior. Collaborators include
58
     *     `grantFactory`, `requestFactory`, `httpClient`, and `randomFactory`.
59
     *     Individual providers may introduce more collaborators, as needed.
60
     */
61 24
    public function __construct(array $options = [], array $collaborators = [])
62
    {
63 24
        if (isset($options['encryptionKeyPath'])) {
64 2
            $this->setEncryptionKeyPath($options['encryptionKeyPath']);
65 2
            unset($options['encryptionKeyPath']);
66 2
        }
67 24
        parent::__construct($options, $collaborators);
68 24
    }
69
70
    /**
71
     * Attempts to decrypt the given response.
72
     *
73
     * @param  string|array|null $response
74
     *
75
     * @return string|array|null
76
     */
77 6
    public function decryptResponse($response)
78
    {
79 6
        if (is_string($response)) {
80 4
            if ($this->encryptionAlgorithm && $this->encryptionKey) {
81
                try {
82 2
                    $response = json_decode(
83 2
                        json_encode(
84 2
                            JWT::decode(
85 2
                                $response,
86 2
                                $this->encryptionKey,
87 2
                                array($this->encryptionAlgorithm)
88 2
                            )
89 2
                        ),
90
                        true
91 2
                    );
92 2
                } catch (Exception $e) {
93
                    throw new EncryptionConfigurationException(
94
                        $e->getMessage(),
95
                        400,
96
                        $e
97
                    );
98
                }
99 2
            } else {
100 2
                throw new EncryptionConfigurationException(
101
                    'The given response may be encrypted and sufficient '.
102 2
                    'encryption configuration has not been provided.',
103
                    400
104 2
                );
105
            }
106 2
        }
107
108 4
        return $response;
109
    }
110
111
    /**
112
     * Get authorization url to begin OAuth flow
113
     *
114
     * @return string
115
     */
116 6
    public function getBaseAuthorizationUrl()
117
    {
118 6
        return $this->getBaseUrlWithRealm().'/protocol/openid-connect/auth';
119
    }
120
121
    /**
122
     * Get access token url to retrieve token
123
     *
124
     * @param  array $params
125
     *
126
     * @return string
127
     */
128 14
    public function getBaseAccessTokenUrl(array $params)
129
    {
130 14
        return $this->getBaseUrlWithRealm().'/protocol/openid-connect/token';
131
    }
132
133
    /**
134
     * Get provider url to fetch user details
135
     *
136
     * @param  AccessToken $token
137
     *
138
     * @return string
139
     */
140 6
    public function getResourceOwnerDetailsUrl(AccessToken $token)
141
    {
142 6
        return $this->getBaseUrlWithRealm().'/protocol/openid-connect/userinfo';
143
    }
144
145
    /**
146
     * Creates base url from provider configuration.
147
     *
148
     * @return string
149
     */
150 18
    protected function getBaseUrlWithRealm()
151
    {
152 18
        return $this->authServerUrl.'/realms/'.$this->realm;
153
    }
154
155
    /**
156
     * Get the default scopes used by this provider.
157
     *
158
     * This should not be a complete list of all scopes, but the minimum
159
     * required for the provider user interface!
160
     *
161
     * @return string[]
162
     */
163 4
    protected function getDefaultScopes()
164
    {
165 4
        return ['name', 'email'];
166
    }
167
168
    /**
169
     * Check a provider response for errors.
170
     *
171
     * @throws IdentityProviderException
172
     * @param  ResponseInterface $response
173
     * @param  string $data Parsed response data
174
     * @return void
175
     */
176 10
    protected function checkResponse(ResponseInterface $response, $data)
177
    {
178 10
        if (!empty($data['error'])) {
179 2
            $error = $data['error'].': '.$data['error_description'];
180 2
            throw new IdentityProviderException($error, 0, $data);
181
        }
182 8
    }
183
184
    /**
185
     * Generate a user object from a successful user details request.
186
     *
187
     * @param array $response
188
     * @param AccessToken $token
189
     * @return KeycloakResourceOwner
190
     */
191 4
    protected function createResourceOwner(array $response, AccessToken $token)
192
    {
193 4
        return new KeycloakResourceOwner($response);
194
    }
195
196
    /**
197
     * Requests and returns the resource owner of given access token.
198
     *
199
     * @param  AccessToken $token
200
     * @return KeycloakResourceOwner
201
     */
202 6
    public function getResourceOwner(AccessToken $token)
203
    {
204 6
        $response = $this->fetchResourceOwnerDetails($token);
205
206 6
        $response = $this->decryptResponse($response);
207
208 4
        return $this->createResourceOwner($response, $token);
0 ignored issues
show
Bug introduced by
It seems like $response defined by $this->decryptResponse($response) on line 206 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...
209
    }
210
211
    /**
212
     * Updates expected encryption algorithm of Keycloak instance.
213
     *
214
     * @param string  $encryptionAlgorithm
215
     *
216
     * @return Keycloak
217
     */
218 4
    public function setEncryptionAlgorithm($encryptionAlgorithm)
219
    {
220 4
        $this->encryptionAlgorithm = $encryptionAlgorithm;
221
222 4
        return $this;
223
    }
224
225
    /**
226
     * Updates expected encryption key of Keycloak instance.
227
     *
228
     * @param string  $encryptionKey
229
     *
230
     * @return Keycloak
231
     */
232 4
    public function setEncryptionKey($encryptionKey)
233
    {
234 4
        $this->encryptionKey = $encryptionKey;
235
236 4
        return $this;
237
    }
238
239
    /**
240
     * Updates expected encryption key of Keycloak instance to content of given
241
     * file path.
242
     *
243
     * @param string  $encryptionKeyPath
244
     *
245
     * @return Keycloak
246
     */
247 2
    public function setEncryptionKeyPath($encryptionKeyPath)
248
    {
249
        try {
250 2
            $this->encryptionKey = file_get_contents($encryptionKeyPath);
251 2
        } catch (Exception $e) {
252
            // Not sure how to handle this yet.
253
        }
254
255 2
        return $this;
256
    }
257
}
258