Changes
Title
unchanged
JWT authentication tutorial
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
changed
authentication,auth,jwt
Content
changed
[...]
This token is generated upon login only, and is stored in the table `user_refresh_token`.
A user may have several RefreshToken in the database.
### Scenarios
#### User logs in for the first time, via the `/auth/login` endpoint:
In our `actionLogin()` method two things happens, if the credentials are correct:[...]
The RefreshToken is in your cookies, but can't be read/accessed/tempered with through Javascript (since it is `httpOnly`).
#### Token expired:
After some time, the JWT will eventually expire. Your API have to return `401 - Unauthorized` in this case.[...]
Your HTTP client must take this new JWT, replace it in `localStorage`, and then cycle through the request queue and replay all failed requests.
#### My laptop got stolen:
If you set up an `/auth/sessions` endpoint, that returns all the current user's RefreshTokens, you can then display[...]
#### Why do we trust the JWT blindly?
This is by design the purpose of JWT. It is secure enough to be trustable.[...]
## Implementation Steps
### Prerequisites
* Yii2 installed[...]
### Step-by-step setup
- Create an ActiveRecord model for the table `user_refresh_tokens`. We'll use the class name `app\models\UserRefreshToken`.[...]
```php
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => \sizeg\jwt\JwtHttpBearerAuth::class,
'except' => [[...]
'urf_created' => gmdate('Y-m-d H:i:s'),
]);
if (!$userRefreshToken->save()
;) {
throw new \yii\web\ServerErrorHttpException('Failed to save the refresh token: '. $userRefreshToken->getErrorSummary(true));
}
// Send the refresh-token to the user in a HttpOnly cookie that Javascript can never read and that's limited by path
Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => 'refresh-token',
'value' => $refreshToken,[...]