asinfotrack/yii2-jwt

Yii2-jwt 是一组用于处理 JSON Web Tokens 的功能。

安装数: 15,752

依赖者: 0

建议者: 0

安全: 0

星标: 3

关注者: 6

分支: 1

开放问题: 0

类型:yii2-extension

0.8.0 2018-02-27 08:20 UTC

This package is auto-updated.

Last update: 2024-09-08 22:11:34 UTC


README

Yii2-jwt 是一组用于处理 JSON Web Tokens 的功能。它是一个围绕 JWT 扩展 firebase/php-jwt 的包装器,可以作为特质附加到任何类。令牌数据封装在辅助类中,并以数组的形式表示,这与 Yii2 应用程序中的常规做法一致。

还可以查看 firebase jwt 扩展的存储库

安装

基本安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

$ composer require asinfotrack/yii2-jwt

或将其添加到您的 composer.json 文件的 require 部分:

"asinfotrack/yii2-jwt": "~0.8.0"

用法

简单地将 JwtTokenTrait 添加到您希望创建令牌的任何类中。通常这是用户类。

class User extends \yii\db\ActiveRecorde implements \yii\web\IdentityInterface
{
	
	//...
	
	use JwtTokenTrait;
	
	//...
	
	/**
	 * @inheritdoc
	 */
	public static function findIdentityByAccessToken($token, $type=null)
	{
		/* @var $result \asinfotrack\yii2\jwt\helpers\JwtTokenDecodingResult */
	
		try {
			//try decoding the token
			$result = $this->decodeJwtToken($token, Yii::$app->params['myJwtTokenSecret'], true, true);
		} catch (JwtException $e) {
			//check if token is valid but expired
			if ($e instanceof \asinfotrack\yii2\jwt\exceptions\JwtExpiredException) {
				//delete expired token from db
			}
			
			//return null to signal user could not be found
			return null;
		}
		
		//token was valid so we can extract the id
		$modelId = $result->getJti();
		
		//return the user model or null if not found
		return static::findOne($modelId);
	}
	
	//...
	
	/**
	 * Create a token for the current user model instance. You might want to persist
	 * the result in a token table to keep track of the tokens created.
	 *
	 * @return string the created token
	 */
	protected function createTokenForUser()
	{
		/* @var $request \asinfotrack\yii2\jwt\helpers\JwtTokenIssueRequest */
	
		//optional request if additional data is required (eg user roles)
		$userRoles = array_keys(Yii::$app->authManager->getRolesByUser($this->id));
		$request = new JwtIssueRequest();
		$request->setPayloadEntry('roles', $userRoles);
		
		return $this->createJwtToken($this->id, Yii::$app->params['myJwtTokenSecret'], $request);
	}
	
	//...
	
}

更新日志

[v0.8.0] (进行中)
  • 主要类处于稳定状态
  • 从现在开始,将以向后兼容的方式添加更多功能
  • 所有破坏性变更都将导致新的小版本。