Repository: sizeg/yii2-jwt
Branch: master
Commit: 40fc06e8eb7f
Files: 12
Total size: 30.5 KB
Directory structure:
gitextract_exru28qr/
├── .gitattributes
├── .gitignore
├── .travis.yml
├── Jwt.php
├── JwtHttpBearerAuth.php
├── JwtValidationData.php
├── README.md
├── composer.json
├── phpunit.xml.dist
└── tests/
├── JwtTest.php
├── TestCase.php
└── bootstrap.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Ignore all test and documentation for archive
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/phpunit.xml.dist export-ignore
/tests export-ignore
================================================
FILE: .gitignore
================================================
# phpstorm project files
.idea
# netbeans project files
nbproject
# zend studio for eclipse project files
.buildpath
.project
.settings
# windows thumbnail cache
Thumbs.db
# composer vendor dir
/vendor
/composer.lock
# composer itself is not needed
composer.phar
# Mac DS_Store Files
.DS_Store
# phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml
# local tests configuration
/tests/data/config.local.php
# runtime cache
/tests/runtime
================================================
FILE: .travis.yml
================================================
language: php
php:
- 5.6
- 7.0
- 7.1
- 7.2
# faster builds on new travis setup not using sudo
sudo: false
install:
# - composer global require "fxp/composer-asset-plugin:~1.4.4"
- export PATH="$HOME/.composer/vendor/bin:$PATH"
- composer install --prefer-dist --no-interaction
#script:
# - phpunit
================================================
FILE: Jwt.php
================================================
<?php
namespace sizeg\jwt;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Claim\Factory as ClaimFactory;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Parsing\Decoder;
use Lcobucci\JWT\Parsing\Encoder;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData;
use Yii;
use yii\base\Component;
use yii\base\InvalidArgumentException;
/**
* JSON Web Token implementation, based on this library:
* https://github.com/lcobucci/jwt
*
* @author Dmitriy Demin <sizemail@gmail.com>
* @since 1.0.0-a
*/
class Jwt extends Component
{
/**
* @var array Supported algorithms
*/
public $supportedAlgs = [
'HS256' => \Lcobucci\JWT\Signer\Hmac\Sha256::class,
'HS384' => \Lcobucci\JWT\Signer\Hmac\Sha384::class,
'HS512' => \Lcobucci\JWT\Signer\Hmac\Sha512::class,
'ES256' => \Lcobucci\JWT\Signer\Ecdsa\Sha256::class,
'ES384' => \Lcobucci\JWT\Signer\Ecdsa\Sha384::class,
'ES512' => \Lcobucci\JWT\Signer\Ecdsa\Sha512::class,
'RS256' => \Lcobucci\JWT\Signer\Rsa\Sha256::class,
'RS384' => \Lcobucci\JWT\Signer\Rsa\Sha384::class,
'RS512' => \Lcobucci\JWT\Signer\Rsa\Sha512::class,
];
/**
* @var Key|string $key The key
*/
public $key;
/**
* @var string|array|callable \sizeg\jwtJwtValidationData
* @see [[Yii::createObject()]]
*/
public $jwtValidationData = JwtValidationData::class;
/**
* @see [[Lcobucci\JWT\Builder::__construct()]]
* @param Encoder|null $encoder
* @param ClaimFactory|null $claimFactory
* @return Builder
*/
public function getBuilder(Encoder $encoder = null, ClaimFactory $claimFactory = null)
{
return new Builder($encoder, $claimFactory);
}
/**
* @see [[Lcobucci\JWT\Parser::__construct()]]
* @param Decoder|null $decoder
* @param ClaimFactory|null $claimFactory
* @return Parser
*/
public function getParser(Decoder $decoder = null, ClaimFactory $claimFactory = null)
{
return new Parser($decoder, $claimFactory);
}
/**
* @see [[Lcobucci\JWT\ValidationData::__construct()]]
* @return ValidationData
*/
public function getValidationData()
{
return Yii::createObject($this->jwtValidationData)->getValidationData();
}
/**
* @param string $alg
* @return Signer
*/
public function getSigner($alg)
{
$class = $this->supportedAlgs[$alg];
return new $class();
}
/**
* @param strng $content
* @param string|null $passphrase
* @return Key
*/
public function getKey($content = null, $passphrase = null)
{
$content = $content ?: $this->key;
if ($content instanceof Key) {
return $content;
}
return new Key($content, $passphrase);
}
/**
* Parses the JWT and returns a token class
* @param string $token JWT
* @param bool $validate
* @param bool $verify
* @return Token|null
* @throws \Throwable
*/
public function loadToken($token, $validate = true, $verify = true)
{
try {
$token = $this->getParser()->parse((string) $token);
} catch (\RuntimeException $e) {
Yii::warning('Invalid JWT provided: ' . $e->getMessage(), 'jwt');
return null;
} catch (\InvalidArgumentException $e) {
Yii::warning('Invalid JWT provided: ' . $e->getMessage(), 'jwt');
return null;
}
if ($validate && !$this->validateToken($token)) {
return null;
}
if ($verify && !$this->verifyToken($token)) {
return null;
}
return $token;
}
/**
* Validate token
* @param Token $token token object
* @param int|null $currentTime
* @return bool
*/
public function validateToken(Token $token, $currentTime = null)
{
$validationData = $this->getValidationData();
if ($currentTime !== null) {
$validationData->setCurrentTime($currentTime);
}
return $token->validate($validationData);
}
/**
* Validate token
* @param Token $token token object
* @return bool
* @throws \Throwable
*/
public function verifyToken(Token $token)
{
$alg = $token->getHeader('alg');
if (empty($this->supportedAlgs[$alg])) {
throw new InvalidArgumentException('Algorithm not supported');
}
/** @var Signer $signer */
$signer = Yii::createObject($this->supportedAlgs[$alg]);
return $token->verify($signer, $this->key);
}
}
================================================
FILE: JwtHttpBearerAuth.php
================================================
<?php
namespace sizeg\jwt;
use yii\di\Instance;
use yii\filters\auth\AuthMethod;
/**
* JwtHttpBearerAuth is an action filter that supports the authentication method based on JSON Web Token.
*
* You may use JwtHttpBearerAuth by attaching it as a behavior to a controller or module, like the following:
*
* ```php
* public function behaviors()
* {
* return [
* 'bearerAuth' => [
* 'class' => \sizeg\jwt\JwtHttpBearerAuth::className(),
* ],
* ];
* }
* ```
*
* @author Dmitriy Demin <sizemail@gmail.com>
* @since 1.0.0-a
*/
class JwtHttpBearerAuth extends AuthMethod
{
/**
* @var Jwt|string|array the [[Jwt]] object or the application component ID of the [[Jwt]].
*/
public $jwt = 'jwt';
/**
* @var string A "realm" attribute MAY be included to indicate the scope
* of protection in the manner described in HTTP/1.1 [RFC2617]. The "realm"
* attribute MUST NOT appear more than once.
*/
public $realm = 'api';
/**
* @var string Authorization header schema, default 'Bearer'
*/
public $schema = 'Bearer';
/**
* @var callable a PHP callable that will authenticate the user with the JWT payload information
*
* ```php
* function ($token, $authMethod) {
* return \app\models\User::findOne($token->getClaim('id'));
* }
* ```
*
* If this property is not set, the username information will be considered as an access token
* while the password information will be ignored. The [[\yii\web\User::loginByAccessToken()]]
* method will be called to authenticate and login the user.
*/
public $auth;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->jwt = Instance::ensure($this->jwt, Jwt::className());
}
/**
* @inheritdoc
*/
public function authenticate($user, $request, $response)
{
$authHeader = $request->getHeaders()->get('Authorization');
if ($authHeader !== null && preg_match('/^' . $this->schema . '\s+(.*?)$/', $authHeader, $matches)) {
$token = $this->loadToken($matches[1]);
if ($token === null) {
return null;
}
if ($this->auth) {
$identity = call_user_func($this->auth, $token, get_class($this));
} else {
$identity = $user->loginByAccessToken($token, get_class($this));
}
return $identity;
}
return null;
}
/**
* @inheritdoc
*/
public function challenge($response)
{
$response->getHeaders()->set(
'WWW-Authenticate',
"{$this->schema} realm=\"{$this->realm}\", error=\"invalid_token\", error_description=\"The access token invalid or expired\""
);
}
/**
* Parses the JWT and returns a token class
* @param string $token JWT
* @return Token|null
*/
public function loadToken($token)
{
return $this->jwt->loadToken($token);
}
}
================================================
FILE: JwtValidationData.php
================================================
<?php
namespace sizeg\jwt;
use Lcobucci\JWT\ValidationData;
use yii\base\Component;
/**
* Class JwtValidationData
*
* @author SiZE <sizemail@gmail.com>
*/
class JwtValidationData extends Component
{
/**
* @var int|null Current time
*/
public $currentTime = null;
/**
* @var int The leeway (in seconds) to use when validating time claims
*/
public $leeway = 0;
/**
* @var ValidationData
*/
protected $validationData;
/**
* ValidationData constructor.
* @param ValidationData $validationData
* @param array $config
*/
public function __construct($config = [])
{
$this->validationData = new ValidationData($this->currentTime, $this->leeway);
parent::__construct($config);
}
/**
* @return ValidationData
*/
public function getValidationData()
{
return $this->validationData;
}
}
================================================
FILE: README.md
================================================
# Yii2 JWT

This extension provides the [JWT](https://github.com/lcobucci/jwt) integration for the [Yii framework 2.0](http://www.yiiframework.com) (requires PHP 5.6+).
It includes basic HTTP authentication support.
## Table of contents
1. [Installation](#installation)
1. [Dependencies](#dependencies)
1. [Basic usage](#basicusage)
1. [Creating](#basicusage-creating)
1. [Parsing from strings](#basicusage-parsing)
1. [Validating](#basicusage-validating)
1. [Token signature](#tokensign)
1. [Hmac](#tokensign-hmac)
1. [RSA and ECDSA](#tokensign-rsa-ecdsa)
1. [Yii2 basic template example](#yii2basic-example)
<a name="installation"></a>
## Installation
Package is available on [Packagist](https://packagist.org/packages/sizeg/yii2-jwt),
you can install it using [Composer](http://getcomposer.org).
```shell
composer require sizeg/yii2-jwt
```
<a name="dependencies"></a>
## Dependencies
- PHP 5.6+
- OpenSSL Extension
- [lcobucci/jwt 3.3](https://github.com/lcobucci/jwt/tree/3.3)
<a name="basicusage"></a>
## Basic usage
Add `jwt` component to your configuration file,
```php
'components' => [
'jwt' => [
'class' => \sizeg\jwt\Jwt::class,
'key' => 'secret',
],
],
```
Configure the `authenticator` behavior as follows.
```php
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;
}
}
```
Also you can use it with `CompositeAuth` reffer to a [doc](http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html).
<a name="basicusage-creating"></a>
### Creating
Some methods marked as deprecated and will soon backport things from lcobucci/jwt 4.x to create an upgrade path.
Just use the builder to create a new JWT/JWS tokens:
```php
$time = time();
$token = Yii::$app->jwt->getBuilder()
->issuedBy('http://example.com') // Configures the issuer (iss claim)
->permittedFor('http://example.org') // Configures the audience (aud claim)
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
->withClaim('uid', 1) // Configures a new claim, called "uid"
->getToken(); // Retrieves the generated token
$token->getHeaders(); // Retrieves the token headers
$token->getClaims(); // Retrieves the token claims
echo $token->getHeader('jti'); // will print "4f1g23a12aa"
echo $token->getClaim('iss'); // will print "http://example.com"
echo $token->getClaim('uid'); // will print "1"
echo $token; // The string representation of the object is a JWT string (pretty easy, right?)
```
<a name="basicusage-parsing"></a>
### Parsing from strings
Use the parser to create a new token from a JWT string (using the previous token as example):
```php
$token = Yii::$app->jwt->getParser()->parse((string) $token); // Parses from a string
$token->getHeaders(); // Retrieves the token header
$token->getClaims(); // Retrieves the token claims
echo $token->getHeader('jti'); // will print "4f1g23a12aa"
echo $token->getClaim('iss'); // will print "http://example.com"
echo $token->getClaim('uid'); // will print "1"
```
<a name="basicusage-validating"></a>
### Validating
We can easily validate if the token is valid (using the previous token as example):
```php
$data = Yii::$app->jwt->getValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer('http://example.com');
$data->setAudience('http://example.org');
$data->setId('4f1g23a12aa');
var_dump($token->validate($data)); // false, because we created a token that cannot be used before of `time() + 60`
$data->setCurrentTime(time() + 61); // changing the validation time to future
var_dump($token->validate($data)); // true, because validation information is equals to data contained on the token
$data->setCurrentTime(time() + 4000); // changing the validation time to future
var_dump($token->validate($data)); // false, because token is expired since current time is greater than exp
```
We can also use the $leeway parameter to deal with clock skew (see notes below).
If token's claimed time is invalid but the difference between that and the validation time is less than $leeway,
then token is still considered valid
```php
'components' => [
'jwt' => [
'class' => \sizeg\jwt\Jwt:class,
'key' => 'secret',
'jwtValidationData' => [
'class' => \sizeg\jwt\JwtValidationData::class,
// configure leeway
'leeway' => 20,
],
],
],
```
```php
$dataWithLeeway = Yii::$app->jwt->getValidationData();
$dataWithLeeway->setIssuer('http://example.com');
$dataWithLeeway->setAudience('http://example.org');
$dataWithLeeway->setId('4f1g23a12aa');
var_dump($token->validate($dataWithLeeway)); // false, because token can't be used before now() + 60, not within leeway
$dataWithLeeway->setCurrentTime($time + 61); // changing the validation time to future
var_dump($token->validate($dataWithLeeway)); // true, because current time plus leeway is between "nbf" and "exp" claims
$dataWithLeeway->setCurrentTime($time + 3610); // changing the validation time to future but within leeway
var_dump($token->validate($dataWithLeeway)); // true, because current time - 20 seconds leeway is less than exp
$dataWithLeeway->setCurrentTime($time + 4000); // changing the validation time to future outside of leeway
var_dump($token->validate($dataWithLeeway)); // false, because token is expired since current time is greater than exp
```
#### Important
* You have to configure `ValidationData` informing all claims you want to validate the token.
* If `ValidationData` contains claims that are not being used in token or token has claims that are not configured in `ValidationData` they will be ignored by `Token::validate()`.
* `exp`, `nbf` and `iat` claims are configured by default in `ValidationData::__construct()` with the current UNIX time (`time()`).
* The optional `$leeway` parameter of `ValidationData` will cause us to use that number of seconds of leeway when validating the time-based claims,
pretending we are further in the future for the "Issued At" (`iat`) and "Not Before" (`nbf`) claims and pretending we are further in the past
for the "Expiration Time" (`exp`) claim. This allows for situations where the clock of the issuing server has a different time than the clock
of the verifying server, as mentioned in section 4.1 of RFC 7519.
<a name="tokensign"></a>
## Token signature
We can use signatures to be able to verify if the token was not modified after its generation.
This extension implements Hmac, RSA and ECDSA signatures (using 256, 384 and 512).
### Important
Do not allow the string sent to the Parser to dictate which signature algorithm to use,
or else your application will be vulnerable to a [critical JWT security vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries).
The examples below are safe because the choice in `Signer` is hard-coded and cannot be influenced by malicious users.
<a name="tokensign-hmac"></a>
### Hmac
Hmac signatures are really simple to be used:
```php
$jwt = Yii::$app->jwt;
$signer = $jwt->getSigner('HS256');
$key = $jwt->getKey();
$time = time();
$token = $jwt->getBuilder()
->issuedBy('http://example.com') // Configures the issuer (iss claim)
->permittedFor('http://example.org') // Configures the audience (aud claim)
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
->withClaim('uid', 1) // Configures a new claim, called "uid"
->getToken($signer, $key); // Retrieves the generated token
var_dump($token->verify($signer, 'testing 1')); // false, because the key is different
var_dump($token->verify($signer, 'testing')); // true, because the key is the same
```
<a name="tokensign-rsa-ecdsa"></a>
### RSA and ECDSA
RSA and ECDSA signatures are based on public and private keys so you have to generate using the private key and verify using the public key:
```php
$jwt = Yii::$app->jwt;
$signer = $jwt->getSigner('RS256'); // you can use 'ES256' if you're using ECDSA keys
$privateKey = $jwt->getKey('file://{path to your private key}');
$time = time();
$token = $jwt->getBuilder()
->issuedBy('http://example.com') // Configures the issuer (iss claim)
->permittedFor('http://example.org') // Configures the audience (aud claim)
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
->withClaim('uid', 1) // Configures a new claim, called "uid"
->getToken($signer, $privateKey); // Retrieves the generated token
$publicKey = $jwt->getKey('file://{path to your public key}');
var_dump($token->verify($signer, $publicKey)); // true when the public key was generated by the private one =)
```
**It's important to say that if you're using RSA keys you shouldn't invoke ECDSA signers (and vice-versa), otherwise ```sign()``` and ```verify()``` will raise an exception!**
<a name="yii2basic-example"></a>
## Yii2 basic template example
### Basic scheme
1. Client send credentials. For example, login + password
2. Backend validate them
3. If credentials is valid client receive token
4. Client store token for the future requests
### Step-by-step usage example
1. Create Yii2 application
In this example we will use [basic template](https://github.com/yiisoft/yii2-app-basic), but you can use [advanced template](https://github.com/yiisoft/yii2-app-advanced) in the same way.
```shell
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic yii2-jwt-test
```
2. Install component
```shell
composer require sizeg/yii2-jwt
```
3. Add to config/web.php into `components` section
```php
$config = [
'components' => [
// other default components here..
'jwt' => [
'class' => \sizeg\jwt\Jwt::class,
'key' => 'secret',
// You have to configure ValidationData informing all claims you want to validate the token.
'jwtValidationData' => \app\components\JwtValidationData::class,
],
],
];
```
4. Create JwtValidationData class. Where you have to configure ValidationData informing all claims you want to validate the token.
```php
<?php
namespace app\components;
class JwtValidationData extends \sizeg\jwt\JwtValidationData
{
/**
* @inheritdoc
*/
public function init()
{
$this->validationData->setIssuer('http://example.com');
$this->validationData->setAudience('http://example.org');
$this->validationData->setId('4f1g23a12aa');
parent::init();
}
}
```
5. Change method `app\models\User::findIdentityByAccessToken()`
```php
/**
* {@inheritdoc}
* @param \Lcobucci\JWT\Token $token
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['id'] === (string) $token->getClaim('uid')) {
return new static($user);
}
}
return null;
}
```
6. Create controller
```php
<?php
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()
{
/** @var Jwt $jwt */
$jwt = Yii::$app->jwt;
$signer = $jwt->getSigner('HS256');
$key = $jwt->getKey();
$time = time();
// Previous implementation
/*
$token = $jwt->getBuilder()
->setIssuer('http://example.com')// Configures the issuer (iss claim)
->setAudience('http://example.org')// Configures the audience (aud claim)
->setId('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
->setIssuedAt(time())// Configures the time that the token was issue (iat claim)
->setExpiration(time() + 3600)// Configures the expiration time of the token (exp claim)
->set('uid', 100)// Configures a new claim, called "uid"
->sign($signer, $jwt->key)// creates a signature using [[Jwt::$key]]
->getToken(); // Retrieves the generated token
*/
// Adoption for lcobucci/jwt ^4.0 version
$token = $jwt->getBuilder()
->issuedBy('http://example.com')// Configures the issuer (iss claim)
->permittedFor('http://example.org')// Configures the audience (aud claim)
->identifiedBy('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
->issuedAt($time)// Configures the time that the token was issue (iat claim)
->expiresAt($time + 3600)// Configures the expiration time of the token (exp claim)
->withClaim('uid', 100)// Configures a new claim, called "uid"
->getToken($signer, $key); // Retrieves the generated token
return $this->asJson([
'token' => (string)$token,
]);
}
/**
* @return \yii\web\Response
*/
public function actionData()
{
return $this->asJson([
'success' => true,
]);
}
}
```
7. Send simple login request to get token. Here we does not send any credentials to simplify example. As we specify in `authenticator` behavior action `login` as optional the `authenticator` skip auth check for that action.

8. First of all we try to send request to rest/data without token and getting error `Unauthorized`

9. Then we retry request but already adding `Authorization` header with our token

================================================
FILE: composer.json
================================================
{
"name": "sizeg/yii2-jwt",
"description": "JWT based on Icobucci",
"type": "yii2-extension",
"keywords": ["yii2", "yii 2", "jwt"],
"authors": [
{
"name": "Dmitriy Demin",
"email": "sizemail@gmail.com",
"homepage": "https://sizeg.tk"
}
],
"license": "BSD-3-Clause",
"require": {
"php": ">=5.6.0",
"lcobucci/jwt": "~3.3.0",
"yiisoft/yii2": "~2.0.0"
},
"require-dev": {
"phpunit/phpunit": "^4.8"
},
"autoload": {
"psr-4": {
"sizeg\\jwt\\": ""
}
},
"autoload-dev": {
"psr-4": {
"sizeg\\jwt\\tests\\": "tests/"
}
},
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
}
================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="utf-8"?>
<phpunit bootstrap="./tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
</whitelist>
</filter>
</phpunit>
================================================
FILE: tests/JwtTest.php
================================================
<?php
namespace sizeg\jwt\tests;
class JwtTest extends TestCase
{
/**
* Secret key
*/
const SECRET = 'secret';
/**
* Issuer
*/
const ISSUER = 'http://example.com';
/**
* Audience
*/
const AUDIENCE = 'http://example.org';
/**
* Id
*/
const ID = '4f1g23a12aa';
/**
* @var Jwt
*/
public $jwt;
/**
* @ineritdoc
*/
public function setUp()
{
$this->jwt = \Yii::createObject(\sizeg\jwt\Jwt::class, [
['key' => self::SECRET]
]);
}
/**
* @return Sha256 signer
*/
public function getSignerSha256()
{
return new \Lcobucci\JWT\Signer\Hmac\Sha256();
}
/**
* @return Token created token
*/
public function createTokenWithSignature()
{
return $this->jwt->getBuilder()->setIssuer(self::ISSUER) // Configures the issuer (iss claim)
->setAudience(self::AUDIENCE) // Configures the audience (aud claim)
->setId(self::ID, true) // Configures the id (jti claim), replicating as a header item
->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
->setExpiration(time() + 3600) // Configures the expiration time of the token (nbf claim)
->set('uid', 1) // Configures a new claim, called "uid"
->sign($this->getSignerSha256(), $this->jwt->key) // creates a signature using "testing" as key
->getToken(); // Retrieves the generated token
}
/**
* @return ValidationData
*/
public function getValidationData()
{
$data = $this->jwt->getValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer(self::ISSUER);
$data->setAudience(self::AUDIENCE);
$data->setId(self::ID);
return $data;
}
/**
* Validate token with signature
*/
public function testValidateTokenWithSignature()
{
$token = $this->createTokenWithSignature();
$data = $this->getValidationData();
$is_verify = $token->verify($this->getSignerSha256(), $this->jwt->key);
$is_valid = $token->validate($data); // true, because validation information is equals to data contained on the token
$this->assertTrue($is_verify && $is_valid);
}
/**
* Validate token timeout with signature
*/
public function testValidateTokenTimeoutWithSignature()
{
$token = $this->createTokenWithSignature();
$data = $this->getValidationData();
$data->setCurrentTime(time() + 4000); // changing the validation time to future
$is_verify = $token->verify($this->getSignerSha256(), $this->jwt->key);
$is_valid = $token->validate($data); // false, because token is expired since current time is greater than exp
$this->assertFalse($is_verify && $is_valid);
}
}
================================================
FILE: tests/TestCase.php
================================================
<?php
namespace sizeg\jwt\tests;
use yii\console\Application;
/**
* Class TestCase
* @author SiZE
*/
class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* @inheritdoc
*/
protected function setUp()
{
parent::setUp();
$this->mockApplication();
}
/**
* @inheritdoc
*/
protected function tearDown()
{
$this->destroyApplication();
parent::tearDown();
}
protected function mockApplication()
{
new Application([
'id' => 'testapp',
'basePath' => __DIR__,
'vendorPath' => dirname(__DIR__) . '/vendor',
'runtimePath' => __DIR__ . '/runtime',
]);
}
protected function destroyApplication()
{
\Yii::$app = null;
}
}
================================================
FILE: tests/bootstrap.php
================================================
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
gitextract_exru28qr/
├── .gitattributes
├── .gitignore
├── .travis.yml
├── Jwt.php
├── JwtHttpBearerAuth.php
├── JwtValidationData.php
├── README.md
├── composer.json
├── phpunit.xml.dist
└── tests/
├── JwtTest.php
├── TestCase.php
└── bootstrap.php
SYMBOL INDEX (29 symbols across 5 files)
FILE: Jwt.php
class Jwt (line 25) | class Jwt extends Component
method getBuilder (line 60) | public function getBuilder(Encoder $encoder = null, ClaimFactory $clai...
method getParser (line 71) | public function getParser(Decoder $decoder = null, ClaimFactory $claim...
method getValidationData (line 80) | public function getValidationData()
method getSigner (line 89) | public function getSigner($alg)
method getKey (line 101) | public function getKey($content = null, $passphrase = null)
method loadToken (line 120) | public function loadToken($token, $validate = true, $verify = true)
method validateToken (line 149) | public function validateToken(Token $token, $currentTime = null)
method verifyToken (line 164) | public function verifyToken(Token $token)
FILE: JwtHttpBearerAuth.php
class JwtHttpBearerAuth (line 27) | class JwtHttpBearerAuth extends AuthMethod
method init (line 65) | public function init()
method authenticate (line 74) | public function authenticate($user, $request, $response)
method challenge (line 98) | public function challenge($response)
method loadToken (line 111) | public function loadToken($token)
FILE: JwtValidationData.php
class JwtValidationData (line 13) | class JwtValidationData extends Component
method __construct (line 36) | public function __construct($config = [])
method getValidationData (line 45) | public function getValidationData()
FILE: tests/JwtTest.php
class JwtTest (line 5) | class JwtTest extends TestCase
method setUp (line 36) | public function setUp()
method getSignerSha256 (line 46) | public function getSignerSha256()
method createTokenWithSignature (line 54) | public function createTokenWithSignature()
method getValidationData (line 69) | public function getValidationData()
method testValidateTokenWithSignature (line 81) | public function testValidateTokenWithSignature()
method testValidateTokenTimeoutWithSignature (line 93) | public function testValidateTokenTimeoutWithSignature()
FILE: tests/TestCase.php
class TestCase (line 11) | class TestCase extends \PHPUnit_Framework_TestCase
method setUp (line 17) | protected function setUp()
method tearDown (line 26) | protected function tearDown()
method mockApplication (line 32) | protected function mockApplication()
method destroyApplication (line 42) | protected function destroyApplication()
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (33K chars).
[
{
"path": ".gitattributes",
"chars": 217,
"preview": "# Ignore all test and documentation for archive\n/.gitattributes export-ignore\n/.gitignore export-ignore\n/.tr"
},
{
"path": ".gitignore",
"chars": 472,
"preview": "# phpstorm project files\n.idea\n\n# netbeans project files\nnbproject\n\n# zend studio for eclipse project files\n.buildpath\n."
},
{
"path": ".travis.yml",
"chars": 316,
"preview": "language: php\n\nphp:\n - 5.6\n - 7.0\n - 7.1\n - 7.2\n\n# faster builds on new travis setup not using sudo\nsudo: false\n\nins"
},
{
"path": "Jwt.php",
"chars": 4708,
"preview": "<?php\n\nnamespace sizeg\\jwt;\n\nuse Lcobucci\\JWT\\Builder;\nuse Lcobucci\\JWT\\Claim\\Factory as ClaimFactory;\nuse Lcobucci\\JWT\\"
},
{
"path": "JwtHttpBearerAuth.php",
"chars": 3088,
"preview": "<?php\n\nnamespace sizeg\\jwt;\n\nuse yii\\di\\Instance;\nuse yii\\filters\\auth\\AuthMethod;\n\n/**\n * JwtHttpBearerAuth is an actio"
},
{
"path": "JwtValidationData.php",
"chars": 926,
"preview": "<?php\n\nnamespace sizeg\\jwt;\n\nuse Lcobucci\\JWT\\ValidationData;\nuse yii\\base\\Component;\n\n/**\n * Class JwtValidationData\n *"
},
{
"path": "README.md",
"chars": 16127,
"preview": "# Yii2 JWT\n\n\n\nThis extension provides the [JWT](https://github.com/lcobucci"
},
{
"path": "composer.json",
"chars": 823,
"preview": "{\n \"name\": \"sizeg/yii2-jwt\",\n \"description\": \"JWT based on Icobucci\",\n\t\"type\": \"yii2-extension\",\n\t\"keywords\": [\"yi"
},
{
"path": "phpunit.xml.dist",
"chars": 533,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<phpunit bootstrap=\"./tests/bootstrap.php\"\n colors=\"true\"\n conver"
},
{
"path": "tests/JwtTest.php",
"chars": 2992,
"preview": "<?php\n\nnamespace sizeg\\jwt\\tests;\n\nclass JwtTest extends TestCase\n{\n\n /**\n * Secret key\n */\n const SECRET "
},
{
"path": "tests/TestCase.php",
"chars": 797,
"preview": "<?php\n\nnamespace sizeg\\jwt\\tests;\n\nuse yii\\console\\Application;\n\n/**\n * Class TestCase\n * @author SiZE\n */\nclass TestCas"
},
{
"path": "tests/bootstrap.php",
"chars": 209,
"preview": "<?php\n \ndefined('YII_DEBUG') or define('YII_DEBUG', true);\ndefined('YII_ENV') or define('YII_ENV', 'test');\n \nrequire(__"
}
]
About this extraction
This page contains the full source code of the sizeg/yii2-jwt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (30.5 KB), approximately 8.2k tokens, and a symbol index with 29 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.