PHP code example of demokrat312 / yii2-jwt

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

    

demokrat312 / yii2-jwt example snippets


'components' => [
    'jwt' => [
        'class' => \sizeg\jwt\Jwt::class,
        'constraints' => [
            function () {
                return new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
                    \Lcobucci\Clock\SystemClock::fromSystemTimezone()
                );
            },
        ],
    ],
],

namespace app\controllers;

class ExampleController extends \yii\rest\Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => \sizeg\jwt\JwtHttpBearerAuth::class,
        ];

        return $behaviors;
    }
}

$now = new DateTimeImmutable();
$algorithm = $this->jwt->getSigner();
$key = $this->jwt->getSignerKey();

$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($algorithm, $key);
   
$token->headers(); // Retrieves the token headers
$token->claims(); // Retrieves the token claims
   
echo $token->headers()->get('foo'); // will print "bar"
echo $token->claims()->get('jti'); // will print "4f1g23a12aa"
echo $token->claims()->get('iss'); // will print "http://example.com"
echo $token->claims()->get('uid'); // will print "1"
echo $token->toString(); // The string representation of the object is a JWT string (pretty easy, right?)

use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;
use Lcobucci\JWT\UnencryptedToken;

try {
    /** @var string $jwt JWT token string */
    $token = Yii::$app->jwt->parse($jwt); // Parses from a string
} catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound $e) {
    echo 'Oh no, an error: ' . $e->getMessage();
}

assert($token instanceof UnencryptedToken);

use \Lcobucci\JWT\Validation\Constraint\IssuedBy;

if (!Yii::$app->jwt->validate($token, new IssuedBy('http://example.com'))) {
    echo 'Invalid token (1)!', PHP_EOL; // will not print this
}

if (!Yii::$app->jwt->validate($token, new IssuedBy('http://example.org'))) {
    echo 'Invalid token (1)!', PHP_EOL; // will print this
}

'components' => [
    'jwt' => [
        'class' => \sizeg\jwt\Jwt::class,
        'signer' => \sizeg\jwt\JwtSigner::HS256,
        'signerKey' => \sizeg\jwt\JwtKey::PLAIN_TEXT,
        'signerKeyContents' => random_bytes(32),
        'signerKeyPassphrase' => 'secret',
        'constraints' => [
            function () {
                // Verifies the claims iat, nbf, and exp, when present (supports leeway configuration)
                return new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
                    \Lcobucci\Clock\SystemClock::fromSystemTimezone()
                );
            },
            function () {
                // Verifies if the token was signed with the expected signer and key
                return new \Lcobucci\JWT\Validation\Constraint\SignedWith(
                    Yii::$app->jwt->getSigner(),
                    Yii::$app->jwt->getSignerKey()
                );
            },
        ],
    ],
],

use \Lcobucci\JWT\Validation\Constraint\SignedWith;

$now = new DateTimeImmutable();

$algorithm = $this->jwt->getSigner(\sizeg\jwt\JwtSigner::HS256);
// ... and key
$contents = random_bytes(32);
$passphrase = 'secret';
$key = $this->jwt->getSignerKey(\sizeg\jwt\JwtKey::PLAIN_TEXT, $contents, $passphrase);

$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($algorithm, $key);
    
if (!Yii::$app->jwt->validate($token, new SignedWith(
    Yii::$app->jwt->getSigner(\sizeg\jwt\JwtSigner::HS256),
    Yii::$app->jwt->getSignerKey(JwtKey::PLAIN_TEXT, $contents, $passphrase)
))) {
    echo 'Invalid token (1)!', PHP_EOL; // will not print this
}

if (!Yii::$app->jwt->validate($token, new SignedWith(
    Yii::$app->jwt->getSigner(\sizeg\jwt\JwtSigner::HS256),
    Yii::$app->jwt->getSignerKey(JwtKey::PLAIN_TEXT, random_bytes(32), 'other-secret')
))) {
    echo 'Invalid token (1)!', PHP_EOL; // will print this
}

use \Lcobucci\JWT\Validation\Constraint\SignedWith;

$now = new DateTimeImmutable();

// you can use 'ES256' if you're using ECDSA keys
$algorithm = Yii::$app->jwt->getSigner(\sizeg\jwt\JwtSigner::RS256);
$privateKey = Yii::$app->jwt->getSignerKey(\sizeg\jwt\JwtKey::FILE, 'file://{path to your private key}');

$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($algorithm, $privateKey);

$publicKey = Yii::$app->jwt->getSignerKey(\sizeg\jwt\JwtKey::FILE, 'file://{path to your public key}');

var_dump(Yii::$app->jwt->validate($token, new SignedWith(
    Yii::$app->jwt->getSigner(\sizeg\jwt\JwtSigner::RS256),
    Yii::$app->jwt->getSignerKey(JwtKey::FILE, $publicKey)
))); // true when the public key was generated by the private one =)

    $config = [
        'components' => [
            // other default components here..
            'jwt' => [
                'class' => \sizeg\jwt\Jwt::class,
                'constraints' => [
                    function () {
                        return new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
                            \Lcobucci\Clock\SystemClock::fromSystemTimezone()
                        );
                    },
                ],
            ],
        ],
    ];
    

        /**
         * {@inheritdoc}
         * @param \Lcobucci\JWT\Token $token
         */
        public static function findIdentityByAccessToken($token, $type = null)
        {
            foreach (self::$users as $user) {
                if ($user['id'] === (string) $token->claims()->get('uid')) {
                    return new static($user);
                }
            }
    
            return null;
        }
    

       
    
       namespace app\controllers;
    
       use sizeg\jwt\Jwt;
       use sizeg\jwt\JwtHttpBearerAuth;
       use Yii;
       use yii\rest\Controller;
    
       class RestController extends Controller
       {
           /**
            * @inheritdoc
            */
           public function behaviors()
           {
               $behaviors = parent::behaviors();
               $behaviors['authenticator'] = [
                   'class' => JwtHttpBearerAuth::class,
                   'optional' => [
                       'login',
                   ],
               ];
    
               return $behaviors;
           }
    
           /**
            * @return \yii\web\Response
            */
           public function actionLogin()
           {
               $now = new DateTimeImmutable();
               $algorithm = $this->jwt->getSigner();
               $key = $this->jwt->getSignerKey();

               /** @var Jwt $jwt */
               $jwt = Yii::$app->jwt;
            
               $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 expiration time of the token (exp claim)
                   ->expiresAt($now->modify('+1 hour'))
                   // Configures a new claim, called "uid"
                   ->withClaim('uid', 100)
                   // Builds a new token
                   ->getToken($algorithm, $key);

            return $this->asJson([
                'token' => $token->toString(),
            ]);
        }
    
        /**
         * @return \yii\web\Response
         */
        public function actionData()
        {
            return $this->asJson([
                'success' => true,
            ]);
        }
    }