All Projects → dersonsena → yii2-jwt-tools

dersonsena / yii2-jwt-tools

Licence: MIT license
An easy way to configure JWT authentication and validation on Yii Framework 2 Projects

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to yii2-jwt-tools

yii2-cashier
Yii2 Cashier provides an interface to Stripe's subscription billing services.
Stars: ✭ 43 (+95.45%)
Mutual labels:  yii2, yii2-extension
content
Content management system for Yii2
Stars: ✭ 54 (+145.45%)
Mutual labels:  yii2, yii2-extension
Yii2 Translate Manager
Translation Manager
Stars: ✭ 221 (+904.55%)
Mutual labels:  yii2, yii2-extension
Crontab
Yii2 extension for crontab support
Stars: ✭ 170 (+672.73%)
Mutual labels:  yii2, yii2-extension
yii2-pgsql
Improved PostgreSQL schemas for Yii2
Stars: ✭ 34 (+54.55%)
Mutual labels:  yii2, yii2-extension
Yii2 Enhanced Gii
Enhanced Yii2 Gii (generator) that generates related Models & CRUD
Stars: ✭ 183 (+731.82%)
Mutual labels:  yii2, yii2-extension
yii2-lets-talk
With this extension you can open chat with someone in popular messengers using the link on your website.
Stars: ✭ 15 (-31.82%)
Mutual labels:  yii2, yii2-extension
Yii2 Assets Auto Compress
Automatic compilation of js + css + html
Stars: ✭ 147 (+568.18%)
Mutual labels:  yii2, yii2-extension
yii2-stat
Yii2 Multi Web Statistic Module (yametrika, google-analytic, own db-counter)
Stars: ✭ 18 (-18.18%)
Mutual labels:  yii2, yii2-extension
yii2-translatable
Translatable behavior aggregates logic of linking translations to the primary model
Stars: ✭ 15 (-31.82%)
Mutual labels:  yii2, yii2-extension
Balance
Balance accounting (bookkeeping) system based on debit and credit principle
Stars: ✭ 162 (+636.36%)
Mutual labels:  yii2, yii2-extension
behavior-trait
Allows handling events via inline declared methods, which can be added by traits
Stars: ✭ 18 (-18.18%)
Mutual labels:  yii2, yii2-extension
Yii2 Workflow
A simple workflow engine for Yii2
Stars: ✭ 157 (+613.64%)
Mutual labels:  yii2, yii2-extension
Ar Softdelete
Soft delete behavior for ActiveRecord
Stars: ✭ 188 (+754.55%)
Mutual labels:  yii2, yii2-extension
Yii2 Comments
Comments module for Yii2
Stars: ✭ 155 (+604.55%)
Mutual labels:  yii2, yii2-extension
install
basic script for project installation
Stars: ✭ 17 (-22.73%)
Mutual labels:  yii2, yii2-extension
Yii2 Rbac
RBAC Manager for Yii 2
Stars: ✭ 128 (+481.82%)
Mutual labels:  yii2, yii2-extension
Yii2 Wx
这可能是yii2中最好用的微信SDK🔥🔥🔥
Stars: ✭ 148 (+572.73%)
Mutual labels:  yii2, yii2-extension
yii2-mailqueue
Yii2 mail queue component for yii2-swiftmailer.
Stars: ✭ 15 (-31.82%)
Mutual labels:  yii2, yii2-extension
ar-search
Provides unified search model for Yii ActiveRecord
Stars: ✭ 31 (+40.91%)
Mutual labels:  yii2, yii2-extension

JWT Tools to Yii Framework 2

GitHub GitHub repo size Packagist Stars Packagist PHP Version Support (specify version) Packagist Downloads

JWT Tools is a toolbox that will help you to configure authentication with JWT 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 through composer.

To install, either run:

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

or add

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

to the require section of your composer.json file.

Usage

Configuration File

Let's guarantee somes application settings are correct. Open your config/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 the JWTSignatureBehavior and HttpBearerAuth behaviors in behaviors() method, such as below:

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;
    }
}

NOTE: in this examples I used Yii::$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

The JWTSignatureBehavior will validate the JWT token sent by Authorization 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 the headerName property, such as below:

class YourCuteController extends Controller
{
    // ...
    public function behaviors()
    {
        $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 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];
    }
    // ...
}

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 here app/models/User as my User Identity, so, let's implement the findIdentityByAccessToken() method of the IdentityInterface interface:

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]);
    }
}

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

Demos

Generating a token

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

use Dersonsena\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 the JWTPayload.

Generating Token with an Active Record

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

use Dersonsena\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 protected] <~~~~
)

The sub property is automatically override to $model->getPrimaryKey() value, following the RFC7519 instructions.

Changing JWT Properties

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

use Dersonsena\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 of contributors 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 the MIT License. See the bundled LICENSE for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].