Completed
Push — master ( ab916e...d476a1 )
by Steven
02:51 queued 01:07
created

Keycloak::createResourceOwner()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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