1. Go to this page and download the library: Download raphaelbsr/yii2-jwt-tools library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use yii\rest\Controller;
class YourCuteController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['jwtValidator'] = [
'class' => JWTSignatureBehavior::class,
'secretKey' => Yii::$app->params['jwt']['secret'],
'except' => ['login'] // it's doesn't run in login action
];
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
'except' => ['login'] // it's doesn't run in login action
];
return $behaviors;
}
}
class YourCuteController extends Controller
{
// ...
public function behaviors()
{
$behaviors['jwtValidator'] = [
'class' => JWTSignatureBehavior::class,
'secretKey' => Yii::$app->params['jwt']['secret'],
'headerName' => 'Auth'
];
}
// ...
}
class YourCuteController extends Controller
{
// ...
public function behaviors()
{
$behaviors['jwtValidator'] = [
'class' => JWTSignatureBehavior::class,
'secretKey' => Yii::$app->params['jwt']['secret'],
'headerName' => 'Auth'
];
}
public function actionLogin()
{
// validation stuff
// find user
$token = JWTTools::build(Yii::$app->params['jwt']['secret'])
->withModel($user, ['name', 'email', 'group'])
->getJWT();
return ['success' => true, 'token' => $token];
}
// ...
}
namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
// ...
public static function findIdentity($id)
{
return static::findOne($id);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
// we don't need to implement this method
}
public function validateAuthKey($authKey)
{
// we don't need to implement this method
}
public static function findIdentityByAccessToken($token, $type = null)
{
$decodedToken = JWTTools::build(Yii::$app->params['jwt']['secret'])
->decodeToken($token);
return static::findOne(['id' => $decodedToken->sub]);
}
}