Skip to content

Commit bdeacca

Browse files
Merge branch 'feature/QUASAR-2638/service-to-backcoffice' into 'master'
Feature/quasar 2638/service to backcoffice See merge request TemplateMonster/PlasmaPlatform/Services/yii2-oauth2-auth-filter!6
2 parents 8699c2f + 756d3a2 commit bdeacca

File tree

3 files changed

+121
-27
lines changed

3 files changed

+121
-27
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
# Changelog
22
All notable changes to this project will be documented in this file.
33

4+
## [1.2] - 2021-08-03
5+
### Added
6+
- caching access token
7+
48
## [1.1.3] - 2021-04-15
59
### Fixed
610
- rawResponse on test run

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,30 @@
44

55
Yii2 module to check validity of oauth2 token and scope access in microservices
66

7+
8+
9+
Installation
10+
------------
11+
12+
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
13+
14+
Either run
15+
16+
```
17+
composer require indigerd/yii2-oauth2-auth-filter "^1.2"
18+
```
19+
20+
or add
21+
22+
```
23+
"indigerd/yii2-oauth2-auth-filter": "^1.2"
24+
```
25+
26+
to the require section of your `composer.json` file.
27+
28+
29+
Usage
30+
-----
31+
732
[CHANGELOG]: ./CHANGELOG.md
8-
[version-badge]: https://img.shields.io/badge/version-1.1.3-blue.svg
33+
[version-badge]: https://img.shields.io/badge/version-1.2-blue.svg

src/authfilter/Module.php

Lines changed: 91 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,12 @@ class Module extends \yii\base\Module
5858
/** @var int $cacheTtl */
5959
public $cacheTtl = 60;
6060

61+
/** @var string $prefixCacheAccessToken */
62+
public $prefixCacheAccessToken = 'access_token_';
6163

6264
/**
6365
* @param ClientInterface $httpClient
66+
*
6467
* @return $this
6568
*/
6669
public function setHttpClient(ClientInterface $httpClient)
@@ -79,18 +82,12 @@ public function init()
7982
throw new InvalidConfigException('Auth server url not configured');
8083
}
8184
$this->setHttpClient(new $this->httpClientClass);
82-
83-
if ($this->cache !== false && $this->cache !== null) {
84-
try {
85-
$this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
86-
} catch (InvalidConfigException $e) {
87-
Yii::warning('Unable to use cache for URL manager: ' . $e->getMessage());
88-
}
89-
}
85+
$this->initCacheInstance();
9086
}
9187

9288
/**
9389
* @param Request $request
90+
*
9491
* @return string
9592
* @throws HttpException
9693
*/
@@ -117,6 +114,7 @@ public function determineAccessToken(Request $request)
117114

118115
/**
119116
* @param Response $response
117+
*
120118
* @return array
121119
* @throws HttpException
122120
*/
@@ -130,7 +128,11 @@ public function validateAuthServerResponce(Response $response)
130128
$error = !empty($tokenInfo['error'])
131129
? $tokenInfo['error']
132130
: 'Invalid access token';
133-
throw new HttpException($response->statusCode, $error, $response->statusCode);
131+
throw new HttpException(
132+
$response->statusCode,
133+
$error,
134+
$response->statusCode
135+
);
134136
}
135137

136138
return $tokenInfo;
@@ -139,6 +141,7 @@ public function validateAuthServerResponce(Response $response)
139141

140142
/**
141143
* @param Request $request
144+
*
142145
* @return array
143146
* @throws HttpException
144147
*/
@@ -156,7 +159,10 @@ public function validateRequest(Request $request)
156159
}
157160
}
158161
try {
159-
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim($this->tokenInfoEndpoint, '/');
162+
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim(
163+
$this->tokenInfoEndpoint,
164+
'/'
165+
);
160166
$response = $this->httpClient->sendRequest(
161167
'GET',
162168
$url,
@@ -167,28 +173,56 @@ public function validateRequest(Request $request)
167173
]
168174
);
169175
} catch (\Exception $e) {
170-
throw new HttpException(503, 'Authentication server not available', 503);
176+
throw new HttpException(
177+
503,
178+
'Authentication server not available',
179+
503
180+
);
171181
}
172182

173183
$afterValidate = $this->validateAuthServerResponce($response);
174184

175185
if ($this->cache instanceof CacheInterface) {
176-
$this->cache->set($accessToken, json_encode($afterValidate), $this->cacheTtl);
186+
$this->cache->set(
187+
$accessToken,
188+
json_encode($afterValidate),
189+
$this->cacheTtl
190+
);
177191
}
178192
return $afterValidate;
179193
}
180194

195+
private function initCacheInstance()
196+
{
197+
if ($this->cache !== false && $this->cache !== null && !($this->cache instanceof CacheInterface)) {
198+
try {
199+
$this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
200+
} catch (InvalidConfigException $e) {
201+
Yii::warning('Unable to use cache for URL manager: ' . $e->getMessage());
202+
}
203+
}
204+
}
205+
206+
181207
/**
182208
* @param string $username
183209
* @param string $password
184210
* @param string $scope
185211
* @param bool $rawResponse
212+
*
186213
* @return array|string
187214
* @throws HttpException
188215
* @throws InvalidConfigException
189216
*/
190-
public function requestAccessToken($username, $password, $scope = '', $rawResponse = false, $grantType = 'password')
191-
{
217+
public function requestAccessToken(
218+
$username,
219+
$password,
220+
$scope = '',
221+
$rawResponse = false,
222+
$grantType = 'password',
223+
$cacheTtl = 0
224+
) {
225+
$this->initCacheInstance();
192226
if ($this->testMode) {
193227
return TestHelper::getTokenInfo($rawResponse);
194228
}
@@ -198,39 +232,67 @@ public function requestAccessToken($username, $password, $scope = '', $rawRespon
198232
if (empty($this->clientSecret)) {
199233
throw new InvalidConfigException('Client secret not configured');
200234
}
235+
236+
$requestParams = [
237+
'grant_type' => $grantType,
238+
'client_id' => $this->clientId,
239+
'client_secret' => $this->clientSecret,
240+
'scope' => $scope,
241+
'username' => $username,
242+
'password' => $password
243+
];
244+
245+
$cacheKey = $this->prefixCacheAccessToken . sha1(json_encode($requestParams));
246+
if ($this->cache instanceof CacheInterface && $cacheTtl > 0) {
247+
$cacheValue = $this->cache->get($cacheKey);
248+
if (!empty($cacheValue)) {
249+
return $rawResponse
250+
? $cacheValue
251+
: json_decode(
252+
$cacheValue,
253+
true
254+
);
255+
}
256+
}
257+
201258
try {
202-
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim($this->tokenIssueEndpoint, '/');
259+
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim(
260+
$this->tokenIssueEndpoint,
261+
'/'
262+
);
203263
$response = $this->httpClient->sendRequest(
204264
'POST',
205265
$url,
206-
[
207-
'grant_type' => $grantType,
208-
'client_id' => $this->clientId,
209-
'client_secret' => $this->clientSecret,
210-
'scope' => $scope,
211-
'username' => $username,
212-
'password' => $password
213-
],
266+
$requestParams,
214267
[
215268
'Accept' => 'application/json'
216269
]
217270
);
218271
} catch (\Exception $e) {
219272
throw new HttpException(503, 'Authentication server not available');
220273
}
274+
275+
if ($this->cache instanceof CacheInterface && $cacheTtl > 0) {
276+
$this->cache->set($cacheKey, $response->content, $cacheTtl);
277+
}
278+
221279
return $rawResponse ? $response : json_decode($response->content, true);
222280
}
223281

224282
/**
225283
* @param string $refresh_token
226284
* @param string $scope
227285
* @param bool $rawResponse
286+
*
228287
* @return array|string
229288
* @throws HttpException
230289
* @throws InvalidConfigException
231290
*/
232-
public function requestAccessByRefreshToken($refresh_token, $scope = '', $rawResponse = false)
233-
{
291+
public function requestAccessByRefreshToken(
292+
$refresh_token,
293+
$scope = '',
294+
$rawResponse = false
295+
) {
234296
if ($this->testMode) {
235297
return TestHelper::getTokenInfo($rawResponse);
236298
}
@@ -241,7 +303,10 @@ public function requestAccessByRefreshToken($refresh_token, $scope = '', $rawRes
241303
throw new InvalidConfigException('Client secret not configured');
242304
}
243305
try {
244-
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim($this->tokenIssueEndpoint, '/');
306+
$url = rtrim($this->authServerUrl, '/') . '/' . ltrim(
307+
$this->tokenIssueEndpoint,
308+
'/'
309+
);
245310
$response = $this->httpClient->sendRequest(
246311
'POST',
247312
$url,

0 commit comments

Comments
 (0)