Home >Backend Development >PHP Tutorial >Detailed explanation of examples of using JWT to create Token in PHP

Detailed explanation of examples of using JWT to create Token in PHP

coldplay.xixi
coldplay.xixiforward
2020-06-09 10:12:045520browse


Detailed explanation of examples of using JWT to create Token in PHP

PHP uses JWT to create a Token simple example

Dependencies

Environment: php 5.5 or above OpenSSL extension

lcobucci/JWT

can be installed using composer

composer require lcobucci/jwt

You can also go directly to GitHub download

GitHub address: https://github.com/lcobucci/jwt

Parameter explanation

##iss (issuer)issuerThe requesting entity can be the information of the user who initiated the request, or The issuer of jwtsub (Subject) sets the subject, similar to the subject when sending an emailaud ( audience)The party receiving jwtexp (expire)tokenExpired time period nbf (not before)The current time is before the nbf setting time, the token cannot be usediat (issued at)tokenCreation time jti (JWT ID)Set a unique identifier for the current token


Preparation before instance

The main dependency references are recorded below:

define('DS', DIRECTORY_SEPARATOR);
define('JWTPath', dirname(__FILE__) . DS);
include_once JWTPath . 'Builder.php';
include_once JWTPath . 'Signer.php';
include_once JWTPath . 'Signer' . DS . 'Keychain.php';
include_once JWTPath . 'Signer' . DS . 'Rsa.php';
include_once JWTPath . 'Signer' . DS . 'Rsa' . DS . 'Sha256.php';

Of course, there are more references in them that you need to add yourself. You can just fill them in one by one according to the error prompts when debugging. There are not many here. wrote.

Example

There are two ways to generate Token using [lcobucci/JWT]. I only tested the second one here.

The first one: Use secret key signature to generate token

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
$builder = new Builder();
$signer = new Sha256();
// 设置发行人
$builder->setIssuer('http://example.com'); 
// 设置接收人
$builder->setAudience('http://example.org'); 
// 设置id
$builder->setId('4f1g23a12aa', true); 
// 设置生成token的时间
$builder->setIssuedAt(time()); 
// 设置在60秒内该token无法使用
$builder->setNotBefore(time() + 60); 
// 设置过期时间
$builder->setExpiration(time() + 3600); 
// 给token设置一个id
$builder->set('uid', 1); 
// 对上面的信息使用sha256算法签名
$builder->sign($signer, '签名key');
// 获取生成的token
$token = $builder->getToken();

Verify Token

use Lcobucci\JWT\Signer\Hmac\Sha256;
$parse = (new Parser())->parse($token);
$signer = new Sha256();
$parse->verify($signer,'签名key');// 验证成功返回true 失败false

The second one: Use RSA and ECDSA signature

RSA and ECDSA signatures are based on public and private keys, so the private key must be used to generate and verify using

use Lcobucci\JWT\Signer\Keychain;
// 注意这里使用的sha256
use Lcobucci\JWT\Signer\Rsa\Sha256; 
$signer = new Sha256();
$keychain = new Keychain();
$builder = new Builder();
$builder->setIssuer('http://example.com');
$builder->setAudience('http://example.org');
$builder->setId('4f1g23a12aa', true);
$builder->setIssuedAt(time());
$builder->setNotBefore(time() + 60);
$builder->setExpiration(time() + 3600);
$builder->set('uid', 1);
// 与上面不同的是这里使用的是你的私钥,并提供私钥的地址
$builder->sign($signer, $keychain->getPrivateKey('file://{私钥地址}'));
$toekn = $builder->getToken();

Finally, it can also be forced to convert To get the pure string Token you want in the form

$toekn = (string) $builder->getToken();

Interaction with the front end can be placed in the returned JSON The format is passed through parameters, and can also be stored in the header Authorization.

Verification Token

$signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
$keychain = new \Lcobucci\JWT\Signer\Keychain();
$parse = new \Lcobucci\JWT\Parser();
$parse->parse((string)$token);
var_dump($token->verify($signer, $keychain->getPublicKey(self::$dir . '/public.key')));
))

Get data

Because the data part can be obtained directly without decryption. Therefore, you can read it directly after verifying that the token is legal. This is also the reason why sensitive information should not be stored in the carrier.

$parse = (new Parser())->parse($token);
// 获取全部信息,返回一个数组,
var_dump($parse->getClaims());
// 获取单条信息
var_dump($parse->getClaim('aud'));

Recommended tutorial: "

PHP Video Tutorial"

The above is the detailed content of Detailed explanation of examples of using JWT to create Token in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:liqingbo.cn. If there is any infringement, please contact admin@php.cn delete