Giter Site home page Giter Site 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

Available versions

bizley/yii2-jwt lcobucci/jwt php
^4.0 ^5.0 >=8.1
^3.0 ^4.0 >=7.4
^2.0 ^3.0 >=7.1

See lcobucci/jwt repo for details about the version.

Installation

Add the package to your composer.json:

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

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

Basic usage

Add jwt component to your configuration file:

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

If you are struggling with the concept of API JWT, here is an EXAMPLE of how to quickly put all pieces together.

Available signers

Symmetric:

  • HMAC (HS256, HS384, HS512)

Asymmetric:

  • RSA (RS256, RS384, RS512)
  • ECDSA (ES256, ES384, ES512)
  • EdDSA (since 3.1.0)
  • BLAKE2B (since 3.4.0)

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.

As stated in lcobucci/jwt documentation: Although BLAKE2B is fantastic due to its performance, it's not JWT standard and won't necessarily be offered by other libraries.

Note on signers and minimum bits requirement

Since lcobucci/jwt 4.2.0 signers require the minimum key length to make sure those are properly secured, otherwise the InvalidKeyProvided is thrown.

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 */,
    'method' => /* method type */,
]

Simple string keys are shortcuts to the following array configs:

  • key starts with @ or file://:

    [
        'key' => /* given key itself */,
        'passphrase' => '',
        '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' => '',
        '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 issued (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
        */,
    ]

Note: By default, this package is not adding any constraints out-of-the-box, you must configure them yourself like in the examples above.

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 - callable 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.
  • throwException - bool (default true) - whether the filter should throw an exception i.e. if the token has an invalid format. If there are multiple auth filters (CompositeAuth) it can make sense to "silent fail" and pass the validation process to the next filter on the composite auth list.

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

dependabot[bot] avatar sizeg avatar nadar avatar anatolyrugalev avatar githubjeka avatar stanfieldr 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.