@@ -180,34 +180,27 @@ use app\components\User;
180
180
use Da\User\AuthClient\Keycloak;
181
181
use Da\User\Event\SocialNetworkAuthEvent;
182
182
use dmstr\usuario\keycloak\controllers\SecurityController;
183
- use yii\authclient\ClientErrorResponseException;
184
- use yii\base\Event;
183
+ use yii\base\Exception;
185
184
use yii\base\InvalidArgumentException;
186
185
use yii\web\Application;
187
186
188
- // Save the auth client info to differentiate afterward from which auth client the user was authenticated
189
- Event::on(SecurityController::class, SocialNetworkAuthEvent::EVENT_AFTER_AUTHENTICATE, function (SocialNetworkAuthEvent $event) {
190
- Yii::$app->getUser()->setAuthSource($event->getClient()->getId());
191
- });
192
-
193
187
return [
194
- 'on ' . Application::EVENT_BEFORE_REQUEST => function () {
188
+ 'on ' . Application::EVENT_BEFORE_REQUEST => function () {
195
189
$user = Yii::$app->getUser();
196
190
$keycloakClientId = 'keycloak';
197
191
if ($user && !$user->getIsGuest() && Yii::$app->getUser()->getAuthSource() === $keycloakClientId) {
198
192
try {
193
+ $jwt = Yii::$app->jwt;
199
194
/** @var Keycloak $keycloak */
200
195
$keycloak = Yii::$app->authClientCollection->getClient($keycloakClientId);
201
- } catch (InvalidArgumentException $exception) {
196
+ // Check if token is valid
197
+ if (!$jwt->validate($keycloak->getAccessToken()->getToken())) {
198
+ // If token is invalid log out the user
199
+ throw new Exception('Access token invalid.');
200
+ }
201
+ } catch (Exception $exception) {
202
202
Yii::error($exception->getMessage());
203
- }
204
- // Check if the token is expired. If so, the getAccessToken throws an error
205
- // INFO: This also triggers a request to keycloak for every request the app makes!
206
- try {
207
- $keycloak->getAccessToken();
208
- } catch (ClientErrorResponseException $exception) {
209
- Yii::info($exception->getMessage());
210
- // If token is expired log out the user
203
+ // Logout user if token cannot be revalidated or is revoked
211
204
$user->logout();
212
205
}
213
206
}
@@ -216,7 +209,20 @@ return [
216
209
'user' => [
217
210
'class' => User::class
218
211
]
219
- ]
212
+ ],
213
+ 'modules' => [
214
+ 'user' => [
215
+ 'controllerMap' => [
216
+ 'security' => [
217
+ 'class' => SecurityController::class,
218
+ 'on ' . SocialNetworkAuthEvent::EVENT_AFTER_AUTHENTICATE => function (SocialNetworkAuthEvent $event) {
219
+ // Save the auth client info to differentiate afterward from which auth client the user was authenticated
220
+ Yii::$app->getUser()->setAuthSource($event->getClient()->getId());
221
+ }
222
+ ]
223
+ ]
224
+ ]
225
+ ]
220
226
];
221
227
```
222
228
0 commit comments