Class luya\admin\components\Jwt

Inheritanceluya\admin\components\Jwt » bizley\jwt\Jwt
Available since version2.0.2

The Jwt component.

To successful configure the jwt component {{Jwt::$key}}, {{Jwt::$apiUserEmail}} and {{Jwt::$identityClass}} can not be null.

'components' => [
    'jwt' => [
         'class' => 'luya\admin\components\Jwt',
         'key' => 'MySecretJwtKey',
         'apiUserEmail' => 'jwtapiuser@luya.io',
         'identityClass' => 'app\modules\myadminmodule\models\User',
    ],
],

An example of create a custom endpoint to retrieve the JWT auth user data:

class MeController extends RestController
{
    public $authOptional = ['login'];

    public function actionLogin()
    {
        $model = new FrontendUser();
        // assuming you have a logic which ensures the user data (mail, pw)
        if ($model->login($_POST)) {
             $token = Yii::$app->jwt->generateToken($model);
             $model->jwt_token = $token;
             $model->update();

             return $this->asJson([
                 'token' => $token,
             ]);
         }
    }

    public function actionData()
    {
         // the authenticated user identity.
         $model = Yii::$app->jwt->identity;
         return $model;
     }
}

Public Properties

Hide inherited properties

Property Type Description Defined By
$apiUserEmail string The email of the LUYA Admin API User which will taken to proxy the jwt requests. luya\admin\components\Jwt
$audience string The audience (aud claim). luya\admin\components\Jwt
$expireTime integer The default expire time when using {{generateToken()}} method. luya\admin\components\Jwt
$identity luya\admin\base\JwtIdentityInterface If an authentification trough jwt token happnes, this variable holds the jwt user identity. luya\admin\components\Jwt
$identityClass string A path or configurable array definition to the class which implements {{luya\admin\base\JwtIdentityInterface}}. luya\admin\components\Jwt
$issuer string The issuer (iss claim). luya\admin\components\Jwt
$key luya\admin\components\Jwt

Public Methods

Hide inherited methods

Method Description Defined By
authenticateUser() Authenticate a user from a given user luya\admin\components\Jwt
generateToken() Method to generate a token from an user with identity interface. luya\admin\components\Jwt
init() luya\admin\components\Jwt

Property Details

Hide inherited properties

$apiUserEmail public property

The email of the LUYA Admin API User which will taken to proxy the jwt requests. This is required as the permissions are set for api users.

public string $apiUserEmail null
$audience public property (available since version 2.3.0)

The audience (aud claim). If not defined the Yii::$app->request->hostInfo will be taken.

public string $audience null
$expireTime public property

The default expire time when using {{generateToken()}} method.

public integer $expireTime 3600
$identity public property

If an authentification trough jwt token happnes, this variable holds the jwt user identity.

$identityClass public property

A path or configurable array definition to the class which implements {{luya\admin\base\JwtIdentityInterface}}.

public string $identityClass null
$issuer public property (available since version 2.3.0)

The issuer (iss claim). If not defined the Yii::$app->request->hostInfo will be taken.

public string $issuer null
$key public property
public $key null

Method Details

Hide inherited methods

authenticateUser() public method

Authenticate a user from a given user

public null|true authenticateUser ( $token )
$token string

                public function authenticateUser($token)
{
    $modelClass = Yii::createObject($this->identityClass);
    if (!ObjectHelper::isInstanceOf($modelClass, JwtIdentityInterface::class, false)) {
        throw new InvalidConfigException("The identityClass must implement the JwtIdentityInterface interface.");
    }
    $auth = $modelClass::loginByJwtToken($token);
    // validation was success, now return the API user in terms of permissions:
    if ($auth && ObjectHelper::isInstanceOf($auth, JwtIdentityInterface::class, false)) {
        // login the api user to the adminuser component.
        $user = ApiUser::find()->andWhere(['email' => $this->apiUserEmail, 'is_api_user' => true])->one();
        if (!$user) {
            throw new InvalidConfigException("The jwt api user could not be found. Ensure `apiUserEmail` with value `{$this->apiUserEmail}` is configured property.");
        }
        $this->identity = $auth;
        return Yii::$app->adminuser->loginByAccessToken($user->auth_token, 'bizley\jwt\JwtHttpBearerAuth');
    }
    return null;
}

            
generateToken() public method

Method to generate a token from an user with identity interface.

Use this method to return the jwt token by a public accessable end point which validates the user credentials.

public function actionUserLogin()
{
    $model = new UserLogin();
    $model->attributes = Yii::$app->request->post();

    if ($model->validate()) {
        $token = Yii::$app->jwt->generateToken($model);
        // depending on whether you like to store the jwt token or use the uid claim to retrieve the user id.
        $model->updateAttributes(['jwt_token' => $token]);
        return $token;
    }

    throw new InvalidRequest("Unable to find and validate the givne User.");
}
public string generateToken ( luya\admin\base\JwtIdentityInterface $user )
$user luya\admin\base\JwtIdentityInterface

The user to generate the access token from.

                public function generateToken(JwtIdentityInterface $user)
{
    $now = new \DateTimeImmutable();
    $token = $this->getBuilder()
        ->issuedBy($this->getIssuer())
        ->permittedFor($this->getAudience())
        ->identifiedBy($user->getId())
        ->withClaim('uid', $user->getId())
        ->issuedAt($now)
        ->expiresAt($now->modify('+'.$this->expireTime . ' minutes'))
        ->getToken(
            $this->getConfiguration()->signer(),
            $this->getConfiguration()->signingKey()
        );
    return $token->toString();
}

            
init() public method

public void init ( )

                public function init(): void
{
    $this->signingKey = $this->key;
    $this->signer = self::HS256;
    if (!$this->apiUserEmail || !$this->identityClass || !$this->key) {
        throw new InvalidConfigException("The attributes apiUserEmail, identityClass and key can not be empty.");
    }
    $this->validationConstraints = [
        new PermittedFor($this->getAudience()),
        new IssuedBy($this->getIssuer()),
    ];
    parent::init();
}