当前位置:网站首页>Tp6 framework integrates JWT for token authentication
Tp6 framework integrates JWT for token authentication
2022-06-30 02:56:00 【Fox catsup】
First step :
Use the command to install
composer require lcobucci/jwt 3.3The second step :
Install the directory under the module for
app\business
The third step :
Conduct JWT Package operation of
namespace app\business;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
class JWT
{
private static $_config = [
'audience' => 'http://www.pyg.com',// recipient
'id' => '3f2g57a92aa',//token Unique identification of , Here is just a simple example
'sign' => 'pinyougou',// Signature key
'issuer' => 'http://adminapi.pyg.com',// Issued by people
'expire' => 3600*24 // The period of validity
];
// Generate token
public static function getToken($user_id){
// Signed by
$signer = new Sha256();
// Get the current timestamp
$time = time();
// Set signer 、 recipient 、 Unique identification 、 The issuance of time 、 Immediate effect 、 Expiration time 、 user id、 Signature
$token = (new Builder())->issuedBy(self::$_config['issuer'])
->canOnlyBeUsedBy(self::$_config['audience'])
->identifiedBy(self::$_config['id'], true)
->issuedAt($time)
->canOnlyBeUsedAfter($time-1)
->expiresAt($time + self::$_config['expire'])
->with('user_id', $user_id)
->sign($signer, self::$_config['sign'])
->getToken();
return (string)$token;
}
// Get... From the requested information token token
public static function getRequestToken()
{
if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
return false;
}
$header = $_SERVER['HTTP_AUTHORIZATION'];
$method = 'bearer';
// Remove token There may be bearer identification
return trim(str_ireplace($method, '', $header));
}
// from token Get users id ( contain token The check )
public static function getUserId($token = null)
{
$user_id = null;
$token = empty($token)?self::getRequestToken():$token;
if (!empty($token)) {
// For cancellation token Add the following if Judging code
$delete_token = cache('delete_token') ?: [];
if(in_array($token, $delete_token)){
//token have been deleted ( Cancellation )
return $user_id;
}
$token = (new Parser())->parse((string) $token);
// verification token
$data = new ValidationData();
$data->setIssuer(self::$_config['issuer']);// Issuer of verification
$data->setAudience(self::$_config['audience']);// Recipient of verification
$data->setId(self::$_config['id']);// verification token identification
if (!$token->validate($data)) {
//token Validation failed
return $user_id;
}
// Verify the signature
$signer = new Sha256();
if (!$token->verify($signer, self::$_config['sign'])) {
// Signature verification failed
return $user_id;
}
// from token Get users id
$user_id = $token->getClaim('user_id');
}
return $user_id;
}
}Step four :
The request header Authorization
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/?s=$1 [QSA,PT,L]
# Add the following
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
</IfModule>Step five :
Establish middleware and verify
public $arr = ['login'];
public function handle($request, \Closure $next)
{
if (!in_array($request->pathinfo(),$this->arr)) {
$token = JWT::getRequestToken();
if(empty($token))
{
return success('token Value is empty ');
}else{
try {
$openid = JWT::getUserId($token);
if(!$openid)
{
return success('token Mistake ');
}
}catch (\Exception $e)
{
return success(' Failure ');
}
}
}
return $next($request);
}边栏推荐
- Global and Chinese markets of liquid optical waveguides 2022-2028: Research Report on technology, participants, trends, market size and share
- Detailed explanation of minimum stack
- Unity TimeLine 数据绑定
- What kind of foreign exchange trading platform is regulated and safe?
- unity的text首列有标点符号咋办
- Azure developer news flash list of events of developers in June
- Global and Chinese market for defense network security 2022-2028: Research Report on technology, participants, trends, market size and share
- High paid programmers & interview questions series 63: talk about the differences between sleep (), yield (), join (), and wait ()
- HTA入门基础教程 | VBS脚本的GUI界面 HTA简明教程 ,附带完整历程及界面美化
- Network neuroscience -- a review of network Neuroscience
猜你喜欢

How to set password complexity and timeout exit function in Oracle

Three solutions to forced hibernation of corporate computers

Differences among digicert, SECTIONO and globalsign code signing certificates

HTA introductory basic tutorial | GUI interface of vbs script HTA concise tutorial, with complete course and interface beautification

Ffmpeg source code

What is an X.509 certificate? 10. 509 certificate working principle and application?

Interrupt operation: abortcontroller learning notes

What files does a CA digital certificate contain? How to view SSL certificate information?

Entering Jiangsu writers and poets carmine Jasmine World Book Day

Unity TimeLine 数据绑定
随机推荐
&nbsp;与空格的区别
Global and Chinese market of relay lens 2022-2028: Research Report on technology, participants, trends, market size and share
CMake教程系列-04-编译相关函数
Precautions for purchasing wildcard SSL certificate
迅為恩智浦iTOP-IMX6開發平臺
Multi card server usage
Summary of knowledge points about eigenvalues and eigenvectors of matrices in Chapter 5 of Linear Algebra (Jeff's self perception)
How to use vant to realize data paging and drop-down loading
Servlet面试题
Global and Chinese market of mobile commerce solutions 2022-2028: Research Report on technology, participants, trends, market size and share
Lua Basics
三层交换机和二层交换机区别是什么
2. successfully solved bug:exception when publishing [Failed to connect and initialize SSH connection...
shell统计某个字符串最后一次出现的位置之前的所有字符串
Study diary: February 15, 2022
How do I enable assembly binding logging- How can I enable Assembly binding logging?
How to modify and add fields when MySQL table data is large
GTK interface programming (II): key components
2022 the action of protecting the net is imminent. Things about protecting the net
Ffmpeg source code