Skip to content

Commit c850553

Browse files
committed
improved readme by alot. Now jwt will be validated
1 parent dec5630 commit c850553

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

README.md

+24-18
Original file line numberDiff line numberDiff line change
@@ -180,34 +180,27 @@ use app\components\User;
180180
use Da\User\AuthClient\Keycloak;
181181
use Da\User\Event\SocialNetworkAuthEvent;
182182
use dmstr\usuario\keycloak\controllers\SecurityController;
183-
use yii\authclient\ClientErrorResponseException;
184-
use yii\base\Event;
183+
use yii\base\Exception;
185184
use yii\base\InvalidArgumentException;
186185
use yii\web\Application;
187186

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-
193187
return [
194-
'on ' . Application::EVENT_BEFORE_REQUEST => function () {
188+
'on ' . Application::EVENT_BEFORE_REQUEST => function () {
195189
$user = Yii::$app->getUser();
196190
$keycloakClientId = 'keycloak';
197191
if ($user && !$user->getIsGuest() && Yii::$app->getUser()->getAuthSource() === $keycloakClientId) {
198192
try {
193+
$jwt = Yii::$app->jwt;
199194
/** @var Keycloak $keycloak */
200195
$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) {
202202
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
211204
$user->logout();
212205
}
213206
}
@@ -216,7 +209,20 @@ return [
216209
'user' => [
217210
'class' => User::class
218211
]
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+
]
220226
];
221227
```
222228

0 commit comments

Comments
 (0)