当前位置:网站首页>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 .
边栏推荐
- (Introduction to database system | Wang Shan) Chapter V database integrity: Exercises
- [about text classification trick] things you don't know
- Anomalies seen during the interview
- 2-Redis架构设计到使用场景-四种部署运行模式(下)
- 不得不会的Oracle数据库知识点(一)
- Axure resources and prototype tool Axure RP 9 download
- [cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
- Introduction to thread pool
- Mobile asynchronous sending SMS verification code solution -efficiency+redis
- Leetcode 121 best time to buy and sell stock (simple)
猜你喜欢
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
[PHP basics] cookie basics, application case code and attack and defense
1-Redis架构设计到使用场景-四种部署运行模式(上)
On covariance of array and wildcard of generic type
What is the GPM scheduler for go?
MPLS experiment
Future source code view -juc series
[cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
功能:求5行5列矩阵的主、副对角线上元素之和。注意, 两条对角线相交的元素只加一次。例如:主函数中给出的矩阵的两条对角线的和为45。
A Kuan food rushed to the Shenzhen Stock Exchange: with annual sales of 1.1 billion, Hillhouse and Maotai CCB are shareholders
随机推荐
ITK learning notes (VII) the position of ITK rotation direction remains unchanged
MySQL 8.0.12 error: error 2013 (HY000): lost connection to MySQL server during query
Network layer - routing
STM32 key light
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
Is it really possible that the monthly salary is 3K and the monthly salary is 15K?
Sorry, Tencent I also refused
A method to solve Bert long text matching
2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)
2022 Software Test Engineer skill list, please check
Global and Chinese markets for instant saliva testing devices 2022-2028: Research Report on technology, participants, trends, market size and share
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
A Kuan food rushed to the Shenzhen Stock Exchange: with annual sales of 1.1 billion, Hillhouse and Maotai CCB are shareholders
Global and Chinese market of breast cancer imaging 2022-2028: Research Report on technology, participants, trends, market size and share
What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers
Entropy and full connection layer
URL (data:image/png; Base64, ivborw0k... Use case
机器学习基础:用 Lasso 做特征选择
Several ways to set up a blog locally [attach relevant software download links]
网上的低佣金链接安全吗?招商证券怎么开户?