当前位置:网站首页>Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
2022-07-04 00:42:00 【Game programming】
1. introduce php-jwt package
composer require firebase/php-jwt 2. Code
Controller files :app\business\Jwt.php
<?phpnamespace app\busines;use Firebase\JWT\JWT;use Firebase\JWT\Key;class JWT{ public function add(){ // Modify your key as needed $key = "example_key"; // Encrypt data , You can customize deletion $payload = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000, "uid" => $uid ); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $jwt = JWT::encode($payload, $key, 'HS256'); return $jwt; $decoded = JWT::decode($jwt, new Key($key, 'HS256')); // It's not necessary print_r($decoded); $decoded_array = (array) $decoded; }} Use... In wechat applets jwt--token
be based on token( token ) User authentication steps :
1、 Users enter their login information
2、 The server verifies whether the information is correct , And return the signed token
3、token Stored on the client , For example, being local storage or cookie in ( The applet is stored in the cache )
4、 After that HTTP Requests will token Add to the request header
// Take it out of the cache tokenconst token = wx.getStorageSync('token') wx.request({ url: '', data:{ }, // request header Head carrying token header: { 'token': token }, success:(res)=>{ console.log(res); this.setData({ bargain:res.data.data }) } }) 5、 Server decoding JWT, And if the token is valid , Then accept the request
6、 Once the user logs off , The token will be destroyed on the client , The key to not having to interact with the server is , Tokens are stateless . The back-end server does not need to save tokens or current session The record of .
Applet header add to touken There are two ways
1、
header:{ // Wechat applet is stored token 'Authorization': token //token It is extracted from the cache },obtain
$token = $_SERVER['HTTP_AUTHORIZATION'];2、
header: { 'token': token, // request header Head carrying token }obtain
$token = $_SERVER['HTTP_TOKEN']; The following code can be ignored
thinkphp6 jwt application token Middleware validation _ Zhongzhong's blog -CSDN Blog
TP6 Study - jwt + Wechat applet verification token_ Mr. Feng -CSDN Blog
Integrate JWT- Realization token User authentication mechanism · tp6 - ThinkPHP6.0 Enterprise best practices · Look at the clouds
<?phpnamespace app\lib;use Firebase\JWT\ExpiredException;use Firebase\JWT\JWT as JWTUtil;use Firebase\JWT\Key;use think\Exception;class JWT{ /** * according to json web token Set the rule generation token * @return \think\response\Json */ public static function createjwt($user_id) { //jwt Issuing key for , verification token It needs to be used $key = md5(env('TOKEN.key')); // The issuance of time $time = time(); // Expiration time $expire = $time + 14400; $token = array( "user_id" => "$user_id", // Issuing organization "iss" => env('TOKEN.iss'), // Issued by "aud" => env('TOKEN.aud'), "iat" => $time, "nbf" => $time, "exp" => $expire ); return json(JWTUtil::encode($token, $key,'HS256')); } /** * verification token * @return \think\response\Json */ public static function verifyjwt($jwt) { // see token Is it overdue ( It will be manually expired in the logic of log out )// $deleteToken=cache("delete_token")?:[];// if (in_array($jwt, $deleteToken)) {// throw new ExpiredException("token Be overdue ","400");// } if (!empty(cache('delete_token')) && in_array($jwt, cache("delete_token"))) { throw new ExpiredException("token Be overdue ","400"); } //jwt Issuing key for , verification token It needs to be used $key = md5(env('TOKEN.key')); try { $jwtAuth = json_encode(JWTUtil::decode($jwt, new Key($key,'HS256'))); $authInfo = json_decode($jwtAuth, true); if (!$authInfo['user_id']) { throw new Exception(' user ID non-existent ','500'); } // Check the signature and return to return json($authInfo); } catch (ExpiredException $e) { throw new Exception('token Be overdue ','500'); } catch (\Exception $e) { throw new Exception($e->getMessage(),'500'); } } // 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)); }} 3. modify public/.htaccess file , adopt apache rewrite , Handle HTTP In the request Authorization Field
( Don't deal with ,php Can't receive HTTP_AUTHORAZATION Field information )
RewriteCond %{HTTP:Authorization} ^(.+)$RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]4. route :app\api\route\api.php
<?phpuse think\facade\Route;Route::rule("jwt","jwt/createjwt","get");Route::rule("verifyjwt","jwt/verifyjwt","post");5. front end : Deposit in
$token=JWT::createjwt($loginData['u_id'])->getData();6. front end : Take out 、 The destruction
public function login(){ // Take out Token value ( In the header) // Empty token Empty the token Deposited in the cache , When used again , Will read the cache for judgment $token=JWT::getRequestToken(); //try { // check token //$data=app\lib\JWT::verifyjwt($token); //}catch (\Exception $exception){ //return fail($exception->getMessage()); //} // Check to see if there is delete_token This key $delete_token = cache('delete_token') ?: []; // Put this token Value in delete_token Array $delete_token[] = $token; // Push the array back into the cache cache('delete_token', $delete_token, 86400); // Destroy succeeded return success(' Destroy succeeded ');}7. Verify success
// Take out token$token=JWT::getRequestToken(); try { // check token $data=JWT::verifyjwt($token); }catch (\Exception $exception){ return fail($exception->getMessage()); }dd($data);8. The effect is shown in the figure


author : Yuan rises and falls
this paper [ ThinkPHP6 Integrate JWT Methods and generation and removal destruction details ] Included in Game programming ️ - PHP, A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome browser .
边栏推荐
- From functools import reduce -- see the use of reduce function from typical examples
- 1-redis architecture design to use scenarios - four deployment and operation modes (Part 1)
- Several ways to set up a blog locally [attach relevant software download links]
- MySQL winter vacation self-study 2022 12 (1)
- 网上的低佣金链接安全吗?招商证券怎么开户?
- [software testing] you haven't mastered these real interview questions of big companies?
- Collation of the most complete Chinese naturallanguageprocessing data sets, platforms and tools
- [leetcode] interview question 17.08 Circus tower
- Beijing invites reporters and media
- UTS | causal reasoning random intervention based on Reinforcement Learning
猜你喜欢

Software testers, how can you quickly improve your testing skills? Ten minutes to teach you

Future source code view -juc series

Shell script three swordsman sed

Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
![[CSDN Q & A] experience and suggestions](/img/db/dff3173dda24ca5740729b54a81153.jpg)
[CSDN Q & A] experience and suggestions

Interview script of Software Test Engineer

Axure resources and prototype tool Axure RP 9 download

Pytest unit test framework: simple and easy to use parameterization and multiple operation modes

Future源码一观-JUC系列

Att & CK actual combat series - red team actual combat - V
随机推荐
ISBN number
Regular expression of shell script value
Analysis and solution of lazyinitializationexception
On covariance of array and wildcard of generic type
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Design of database table foreign key
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
From functools import reduce -- see the use of reduce function from typical examples
1-redis architecture design to use scenarios - four deployment and operation modes (Part 1)
The FISCO bcos console calls the contract and reports an error does not exist
A dichotomy of Valentine's Day
1214 print diamond
Severity code description the project file line prohibits the display of status error c4996 fopen ('fscanf ', StrCmp): this function or variable may be unsafe The most comprehensive solution
Wechat official account and synchronization assistant
Unity Shader入门精要读书笔记 第三章 Unity Shader基础
URL (data:image/png; Base64, ivborw0k... Use case
Development and application of fcitx functional plug-ins
数据库表外键的设计
Qtcharts notes (V) scatter diagram qscatterseries
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!