Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

An easy way to configure JWT authentication and validation on Yii Framework 2 Projects

License

NotificationsYou must be signed in to change notification settings

AstrotechLabs/yii2-jwt-tools

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GitHubGitHub repo sizePackagist StarsPackagist PHP Version Support (specify version)Packagist Downloads

JWT Tools is a toolbox that will help you to configure authentication withJWT token. Not only authentication but also signature validation, the famous secret key.

My biggest motivation to do this was because I didn't see a easy way to setup a simple JWT Validation with some helper functions. I always needed copy and past whole the code to a new project.

Follow the steps below to install and setup in your project.

Installation

The preferred way to install this extension is throughcomposer.

To install, either run:

$ php composer.phar require dersonsena/yii2-jwt-tools

or add

"dersonsena/yii2-jwt-tools": "^1.0"

to therequire section of yourcomposer.json file.

Usage

Configuration File

Let's guarantee somes application settings are correct. Open yourconfig/web.php and setup such as:

'components' => [// ...'request' => ['enableCookieValidation' =>false,    ],'user' => ['identityClass' =>'app\models\User','enableAutoLogin' =>false,'enableSession' =>false,'loginUrl' =>null    ],// ...

Controller

In your controller class, register theJWTSignatureBehavior andHttpBearerAuth behaviors inbehaviors() method, such as below:

useyii\rest\Controller;class YourCuteControllerextends Controller{publicfunctionbehaviors()    {$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;    }}

NOTE: in this examples I usedYii::$app->params['jwt']['secret'] to store my JWT Secret Key, but, I like a lot of the .env files and this information could be stored there

TheJWTSignatureBehavior will validate the JWT token sent byAuthorization HTTP Header. If there are some problem with your token this one it will throw one of Exceptions below:

If for some reason you need to change the HTTP Header name (to be honest I can't see this scenario) you can change this one setting up theheaderName property, such as below:

class YourCuteControllerextends Controller{// ...publicfunctionbehaviors()    {$behaviors['jwtValidator'] = ['class' => JWTSignatureBehavior::class,'secretKey' => Yii::$app->params['jwt']['secret'],'headerName' =>'Auth'        ];    }// ...}

In your login action you need to create a JWT Token to send your response. It's very easy create a token, see below:

class YourCuteControllerextends Controller{// ...publicfunctionbehaviors()    {$behaviors['jwtValidator'] = ['class' => JWTSignatureBehavior::class,'secretKey' => Yii::$app->params['jwt']['secret'],'headerName' =>'Auth'        ];    }publicfunctionactionLogin()    {// validation stuff// find user$token = JWTTools::build(Yii::$app->params['jwt']['secret'])            ->withModel($user, ['name','email','group'])            ->getJWT();return ['success' =>true,'token' =>$token];    }// ...}

Model Identity Class

At this point we know that the token is valid and we can decode this one to authenticate user.

I'm using hereapp/models/User as my User Identity, so, let's implement thefindIdentityByAccessToken() method of theIdentityInterface interface:

namespaceapp\models;useyii\db\ActiveRecord;useyii\web\IdentityInterface;class Userextends ActiveRecordimplements IdentityInterface{// ...publicstaticfunctionfindIdentity($id)    {returnstatic::findOne($id);    }publicfunctiongetId()    {return$this->id;    }publicfunctiongetAuthKey()    {// we don't need to implement this method    }publicfunctionvalidateAuthKey($authKey)    {// we don't need to implement this method    }publicstaticfunctionfindIdentityByAccessToken($token,$type =null)    {$decodedToken = JWTTools::build(Yii::$app->params['jwt']['secret'])            ->decodeToken($token);returnstatic::findOne(['id' =>$decodedToken->sub]);    }}

If all ok, at this point you're able to authenticate with a valid JWT Token.

Demos

Generating a token

You can use theJWTTools methods to make specific things in your project. See some examples below:

useAstrotechLabs\JWTTools\JWTTools;$jwtTools = JWTTools::build('my-secret-key');$token =$jwtTools->getJWT();$payload =$jwtTools->getPayload()->getData();var_dump($token);print_r($payload);

This code will be return something like:

string(248) "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImJlMTgzOTQ4YjJmNjkzZSJ9.eyJzdWIiOiJiZTE4Mzk0OGIyZjY5M2UiLCJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE1ODkxMzEzNjIsImV4cCI6MTU4OTEzNDk2MiwianRpIjoiNTM4NTRiMGQ5MzFkMGVkIn0.-JDBkID1oJ7anC_JLg68AJxbKGK-5ubA83zZlDZYYso"Array(    [sub] => 9c65241853de774    [iss] =>    [aud] =>    [iat] => 1589129672    [exp] => 1589133272    [jti] => a0a98e2364d2721)

NOTE: the->getPayload() returns an instance of theJWTPayload.

Generating Token with an Active Record

You can insert the active record attributes in your payload usingwithModel() method, like this:

useAstrotechLabs\JWTTools\JWTTools;$user =app\models\User::findOne(2);$payload = JWTTools::build('my-secret-key');    ->withModel($user, ['id','name','email'])    ->getPayload()    ->getData();print_r($payload);

This code will be return something like:

Array(    [sub] => 10                   <~~~~    [iss] =>    [aud] =>    [iat] => 1589130028    [exp] => 1589133628    [jti] => 7aba5b7666d7868    [id] => 10                    <~~~~    [name] => Kilderson Sena      <~~~~    [email] => email@email.com.br <~~~~)

Thesub property is automatically override to$model->getPrimaryKey() value, following theRFC7519 instructions.

Changing JWT Properties

You can change the JWT Properties (such asiss,aud etc) adding an array in second method parameter, as below:

useAstrotechLabs\JWTTools\JWTTools;$payload = JWTTools::build('my-secret-key', ['algorithm' =>'ES256','expiration' =>1589069866,//<~~ It will generate the exp property automatically'iss' =>'yourdomain.com','aud' =>'yourdomain.com',]);

Authors

See also the list ofcontributors who participated in this project.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Licence

This package is released under theMIT License. See the bundledLICENSE for details.

About

An easy way to configure JWT authentication and validation on Yii Framework 2 Projects

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp