Giter VIP home page Giter VIP logo

yii2-jwt's Introduction

Latest Stable Version Total Downloads License Infection MSI

JWT Integration For Yii 2

This extension provides the JWT integration for Yii 2 framework.

This is a fork of sizeg/yii2-jwt package

Version 3.x of this package uses lcobucci/jwt v4 and introduces critical BC changes with 2.x.
For 2.x (and lcobucci/jwt v3) install ^2.0.

Installation

Add the package to your composer.json:

{
    "require": {
        "bizley/jwt": "^3.0"
    }
}

and run composer update or alternatively run composer require bizley/jwt:^3.0

Basic usage

Add jwt component to your configuration file:

[
    'components' => [
        'jwt' => [
            'class' => \bizley\jwt\Jwt::class,
            'signer' => ... // Signer ID
            'signingKey' => ... // Secret key string or path to the signing key file
        ],
    ],
],

Available signers

Symmetric:

  • HMAC (HS256, HS384, HS512)

Asymmetric:

  • RSA (RS256, RS384, RS512)
  • ECDSA (ES256, ES384, ES512)

Signer IDs are available as constants (like Jwt::HS256).

You can also provide your own signer, either as an instance of Lcobucci\JWT\Signer or by adding its config to signers and algorithmTypes and using its ID for signer.

Keys

For symmetric signers signingKey is required. For asymmetric ones you also need to set verifyingKey. Keys can be provided as simple strings, configuration arrays, or instances of Lcobucci\JWT\Signer\Key.

Configuration array can be as the following:

[
    'key' => /* key content */,
    'passphrase' => /* key passphrase */,
    'store' => /* storage type */,
    'method' => /* method type */,
]

Simple string keys are shortcuts to the following array configs:

  • key starts with @ or file://:

    [
        'key' => /* given key itself */,
        'passphrase' => '',
        'store' => Jwt::STORE_IN_MEMORY,
        'method' => Jwt::METHOD_FILE,
    ]

    Detecting @ at the beginning assumes Yii alias has been provided so it will be resolved with Yii::getAlias().

  • key doesn't start with @ nor file://:

    [
        'key' => /* given key itself */,
        'passphrase' => '',
        'store' => Jwt::STORE_IN_MEMORY,
        'method' => Jwt::METHOD_PLAIN,
    ]

Issuing a token example:

$now = new \DateTimeImmutable();
/** @var \Lcobucci\JWT\Token\Plain $token */
$token = Yii::$app->jwt->getBuilder()
    // Configures the issuer (iss claim)
    ->issuedBy('http://example.com')
    // Configures the audience (aud claim)
    ->permittedFor('http://example.org')
    // Configures the id (jti claim)
    ->identifiedBy('4f1g23a12aa')
    // Configures the time that the token was issue (iat claim)
    ->issuedAt($now)
    // Configures the time that the token can be used (nbf claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute'))
    // Configures the expiration time of the token (exp claim)
    ->expiresAt($now->modify('+1 hour'))
    // Configures a new claim, called "uid"
    ->withClaim('uid', 1)
    // Configures a new header, called "foo"
    ->withHeader('foo', 'bar')
    // Builds a new token
    ->getToken(
        Yii::$app->jwt->getConfiguration()->signer(),
        Yii::$app->jwt->getConfiguration()->signingKey()
    );
$tokenString = $token->toString();

See https://lcobucci-jwt.readthedocs.io/en/latest/issuing-tokens/ for more info.

Parsing a token

/** @var string $jwt */
/** @var \Lcobucci\JWT\Token $token */
$token = Yii::$app->jwt->parse($jwt);

See https://lcobucci-jwt.readthedocs.io/en/latest/parsing-tokens/ for more info.

Validating a token

You can validate a token or perform an assertion on it (see https://lcobucci-jwt.readthedocs.io/en/latest/validating-tokens/).

For validation use:

/** @var \Lcobucci\JWT\Token | string $token */                                      
/** @var bool $result */
$result = Yii::$app->jwt->validate($token);

For assertion use:

/** @var \Lcobucci\JWT\Token | string $token */                                      
Yii::$app->jwt->assert($token);

You must provide at least one constraint, otherwise Lcobucci\JWT\Validation\NoConstraintsGiven exception will be thrown. There are several ways to provide constraints:

  • directly:

    Yii::$app->jwt->getConfiguration()->setValidationConstraints(/* constaints here */);
  • through component configuration:

    [
        'validationConstraints' => /*
            array of instances of Lcobucci\JWT\Validation\Constraint
            
            or
            array of configuration arrays that can be resolved as Constraint instances
            
            or
            anonymous function that can be resolved as array of Constraint instances with signature
            `function(\bizley\jwt\Jwt $jwt)` where $jwt will be an instance of this component
        */,
    ]

Using component for REST authentication

Configure the authenticator behavior in the controller.

class ExampleController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        
        $behaviors['authenticator'] = [
            'class' => \bizley\jwt\JwtHttpBearerAuth::class,
        ];

        return $behaviors;
    }
}

There are special options available:

  • jwt - string ID of component (default with 'jwt'), component configuration array, or an instance of bizley\jwt\Jwt,
  • auth - \Closure or null (default) - anonymous function with signature function (\Lcobucci\JWT\Token $token) that should return identity of user authenticated with the JWT payload information. If $auth is not provided method yii\web\User::loginByAccessToken() will be called instead.

For other configuration options refer to the Yii 2 Guide.

JWT Usage

Please refer to the lcobucci/jwt Documentation.

JSON Web Tokens

yii2-jwt's People

Contributors

sizeg avatar dependabot[bot] avatar anatolyrugalev avatar githubjeka avatar stanfieldr avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.