PHP code example of agielks / yii2-jwt

1. Go to this page and download the library: Download agielks/yii2-jwt 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/ */

    

agielks / yii2-jwt example snippets


'components' => [
    'jwt' => [
        'class' => \agielks\yii2\jwt\Jwt::class,
        // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(),
        'signer' => 'HS256',
        // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'),
        'key' => 'my-key', ,
    ],
],

namespace app\controllers;

class SiteController extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => \agielks\yii2\jwt\JwtBearerAuth::class,
        ];

        return $behaviors;
    }
}

/* @var $jwt \agielks\yii2\jwt\Jwt */

$now = new DateTimeImmutable();
$jwt = Yii::$app->get('jwt');

$token = $jwt
    ->builder()
    // Configures the issuer (iss claim)
    ->issuedBy('http://example.com')
    // Configures the audience (aud claim)
    ->permittedFor('http://example.org')
    // Configures the id (jti claim)
    ->identifiedBy('62cbfaca6bf7e')
    // Configures the time that the token was issue (iat claim)
    ->issuedAt($now)
    // Configures the time that the token can be used (nbf claim) ken->headers()->get('typ'));

// Retrieves all claims
$token->claims()->all();

// Retrieves jti from claims
$token->claims()->get('jti');

// Print jti from claims
print_r($token->claims()->get('jti'));

/* @var $jwt \agielks\yii2\jwt\Jwt */

$now = new DateTimeImmutable();
$jwt = Yii::$app->get('jwt');

$token = $jwt
    ->builder()
    // ...
    ->expiresAt($now->modify('+1 hour'))
    ->getToken($jwt->signer(), $jwt->key())
    ->toString();

// Parse without validation
$data = $jwt->config()->parser()->parse($token);

// Parse with validation
$data = $jwt->load($token);

// Print all headers
print_r($data->headers()->all());

// Print all claims
print_r($data->claims()->all());

// Validate token
var_dump($data->isExpired($now));
var_dump($data->isExpired($now->modify('+2 hour')));

use \agielks\yii2\jwt\Jwt;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
use \Lcobucci\JWT\Signer\Key\InMemory;
use \Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use \Lcobucci\JWT\Validation\Constraint\SignedWith;
use \Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use \Lcobucci\Clock\SystemClock;

'components' => [
    'jwt' => [
        'class' => Jwt::class,
        'signer' => new Sha256(),
        'key'   => InMemory::plainText('my-key'),
        'constraints' => [
            new LooseValidAt(SystemClock::fromSystemTimezone()),
            new SignedWith(
                new Sha256(),
                InMemory::plainText('my-key')
            ),
            new IdentifiedBy('my-identity'),
        ],
    ],
],

'components' => [
    // other components here...
    'jwt' => [
        'class' => \agielks\yii2\jwt\Jwt::class,
        // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(),
        'signer' => 'HS256',
        // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'),
        'key' => 'my-key', ,
    ],
    // ...
],

/**
 * {@inheritdoc}
 * @param \Lcobucci\JWT\Token $token
 */
public static function findIdentityByAccessToken($token, $type = null)
{
   return static::findOne(['id' => $token->claims()->get('uid')]);
}

/**
 * {@inheritdoc}
 * @param \Lcobucci\JWT\Token $token
 */
public static function findIdentityByAccessToken($token, $type = null)
{
   return static::findOne(['auth_key' => $token->claims()->get('auth_key')]);
}

use agielks\yii2\jwt\JwtBearerAuth;
// Use your own login form
use common\models\LoginForm;
use DateTimeImmutable;
use Yii;
use yii\base\InvalidConfigException;
use yii\filters\Cors;
use yii\rest\Controller;
use yii\web\Response;

/**
 * Class SiteController
 */
class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = ['class' => Cors::class];
        $behaviors['authenticator'] = [
            'class' => JwtBearerAuth::class,
            'optional' => [
                'login',
            ],
        ];

        return $behaviors;
    }

    /**
     * {@inheritdoc}
     */
    protected function verbs()
    {
        return [
            'login' => ['OPTIONS', 'POST'],
        ];
    }

    /**
     * @return array|LoginForm
     * @throws InvalidConfigException
     */
    public function actionLogin()
    {
        $model = new LoginForm();

        if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
            /* @var $jwt \agielks\yii2\jwt\Jwt */

            $now = new DateTimeImmutable();
            $jwt = Yii::$app->get('jwt');
            $user = $model->getUser();

            return $jwt
                ->builder()
                // Configures the issuer (iss claim)
                ->issuedBy('http://example.com')
                // Configures the audience (aud claim)
                ->permittedFor('http://example.org')
                // Configures the id (jti claim)
                ->identifiedBy($user->id)
                // 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)
                // Configures the expiration time of the token (exp claim)
                ->expiresAt($now->modify('+1 hour'))
                // Configures a new claim, called "uid"
                ->withClaim('uid', $user->id)
                // Configures a new claim, called "auth_key"
                ->withClaim('auth_key', $user->auth_key)
                // Returns a signed token to be used
                ->getToken($jwt->signer(), $jwt->key())
                // Convert token to string
                ->toString();
        }

        $model->validate();
        return $model;
    }

    /**
     * Test authentication
     */
    public function actionTest()
    {
        return ['auth' => 'success'];
    }
}