当前位置:网站首页>How to use JWT authentication in thinkphp6
How to use JWT authentication in thinkphp6
2022-06-24 19:14:00 【Yisu cloud】
thinkphp6 How to use jwt authentication
This article mainly explains “thinkphp6 How to use jwt authentication ”, Interested friends might as well come and have a look . The method introduced in this paper is simple and fast , Practical . Now let Xiaobian take you to learn “thinkphp6 How to use jwt authentication ” Well !
thinkphp6 Use jwt
The client uses the user name and password to request login
The server receives the request , Verify user name and password
After successful verification , The server will issue a token, Put this again. token Return to the client
Client received token Then you can store it , For example, put it in cookie in
Each time the client requests resources from the server, it needs to carry the certificate issued by the server token, Can be in cookie perhaps header Middle carry
The server receives the request , Then go to verify the client request token, If the validation is successful , Just return the request data to the client
install jwt Expand
composer require firebase/php-jwt
After installation vender In the catalog firebase Under the folder
call JWT Inside encode and decode Method token And verification token
project app In the catalog common.php Used by global files , Made a public method , Because I am multi - application , So it was written in api Below common.php, You can adjust it according to your own needs
First introduce JWT , Then write two methods , Generate signature verification and verification token.
<?phpuse \Firebase\JWT\JWT;use Firebase\JWT\Key;// Apply public files /** * Generate check * @param $uid user id * @return mixed */function signToken($uid){ $key='abcdefg'; // A user-defined random string, which is commonly used by users in encryption salt salt $token=array( "iss"=>$key, // Issuer Can be null "aud"=>'', // Face users , Can be null "iat"=>time(), // The issuance of time "nbf"=>time(), // when jwt Take effect "exp"=> time()+30, //token Expiration time "data"=>[ // Records of the uid Information about 'uid'=>$uid, ] ); $jwt = JWT::encode($token, $key, "HS256"); // Generated token return $jwt;}/** * verification token * @param $token * @return array|int[] */function checkToken($token){ $key='abcdefg'; // A user-defined random string, which is commonly used by users in encryption salt salt $res['status'] = false; try { JWT::$leeway = 60;// Subtract... From the current time 60, Leave some room for time $decoded = JWT::decode($token, new Key($key, 'HS256')); //HS256 The way , This should correspond to the time of issuance $arr = (array)$decoded; $res['status'] = 200; $res['data'] =(array)$arr['data']; return $res; } catch(\Firebase\JWT\SignatureInvalidException $e) { // Incorrect signature $res['info'] = " Incorrect signature "; return $res; }catch(\Firebase\JWT\BeforeValidException $e) { // Signature can only be used after a certain point in time $res['info'] = "token invalid "; return $res; }catch(\Firebase\JWT\ExpiredException $e) { // token Be overdue $res['info'] = "token Be overdue "; return $res; }catch(Exception $e) { // Other mistakes $res['info'] = " Unknown error "; return $res; }}Use jwt Generate token
/** * Use jwt Generate token character string */ public function setJwtToken() { $uid = input('uid'); // Receive generation token character string Such as :123 $token = signToken($uid); // Generate string : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhYmNkZWZnIiwiYXVkIjoiIiwiaWF0IjoxNjQxNDUwMTU0LCJuYmYiOjE2NDE0NTAxNTcsImV4cCI6MTY0MTQ1NzM1NCwiZGF0YSI6eyJ1aWQiOiIxMjMifX0.I_GAkMsOhtEpIPkizCuQA-b9H6ovSovWx0AwAYI-b0s echo $token;die; } /** * Use jwt verification token character string */ public function checkJwtToken() { $token = input('token'); // Receive generation token character string $result = checkToken($token); // Array ( [status] => 200 [data] => Array ( [uid] => 123 ) ) print_r($result);die; }establish user controller
<?phpdeclare (strict_types = 1);namespace app\api\controller;use think\facade\Db;use think\Request;class User{ public function login(Request $request) { if ($request->isPost()){ $username = $request->param('username','','trim'); $password = $request->param('password','','trim'); // Query the database $user = Db::name('user')->where('username',$username)->find(); if (!$user){ return json(['status' => 'fail','msg' => ' The username does not exist ']); } if ($user['password']!==md5($password)){ return json(['status' => 'fail','msg' => ' Wrong password ']); } $getToken = $this->token($user); return json(['status' => 'success','msg' => ' Landing successful ','token' => $getToken]); } } public function token($user) { $uid = $user['username']; // Receive generation token character string Such as :123 $token = signToken($uid); dd($token); } /** * verification token */ public function chToken() { $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhYmNkZWZnIiwiYXVkIjoiIiwiaWF0IjoxNjQ4MDkwMDkyLCJuYmYiOjE2NDgwOTAwOTIsImV4cCI6MTY0ODA5MDEyMiwiZGF0YSI6eyJ1aWQiOiJcdTVmMjBcdTRlMDlcdTk4Y2UifX0.oJFpNcZ6stMymOCbD-meX0IPEIYLYNcwKxhMItF2cMw'; $result = checkToken($token); // Array ( [status] => 200 [data] => Array ( [uid] => 123 ) ) print_r($result);die; }}The user logs in successfully and returns to the front end token, Front end will be token Store it , Carry this on your head the next time you ask token, Back end accepts token, Verify in the middleware
establish api middleware
<?phpdeclare (strict_types = 1);namespace app\middleware;class Api{ /** * Processing requests * * @param \think\Request $request * @param \Closure $next * @return Response */ public function handle($request, \Closure $next) { //toke Validation of validity $header = $request->header(); // Judge whether there is in the request header token if(!isset($header['token'])){ return json(['code'=>440,'msg'=>'request must with token']); } $token = $header['token']; try { // token legal $token = checkToken($token); }catch (\Exception $e){ return json(['code'=>440,'msg'=>'invalid token']); } return $next($request); }}Here we are , I'm sure you're right “thinkphp6 How to use jwt authentication ” Have a deeper understanding of , You might as well put it into practice ! This is the Yisu cloud website , For more relevant contents, you can enter the relevant channels for inquiry , Pay attention to our , Continue to learn !
边栏推荐
- BSS应用程序云原生部署的8大挑战
- Would you like to ask whether the same multiple tasks of the PgSQL CDC account will have an impact? I now have only one of the three tasks
- 应用程序DDoS攻击原理及防御方法
- Use ado Net call stored procedure
- 目前是不是只cdc 监控mysql 可以拿到新增列的数据 sqlserver不行是吧
- MySQL basic commands
- Stored procedures in sqlserver
- Freeswitch使用originate转dialplan
- subject may not be empty [subject-empty]
- starring V6平台开发接出点流程
猜你喜欢

优维低代码:构件渲染子构件

How to protect biological privacy in the AI era? Overview of the latest "privacy enhancement technology in biometrics" of the Autonomous University of Madrid, comprehensively detailing the biometric p

Introduction and tutorial of SAS planet software

Remote sensing Forum

starring V6平台开发接出点流程
![[leetcode] rotation series (array, matrix, linked list, function, string)](/img/9e/079311df16fa8e28708f4e050e531f.png)
[leetcode] rotation series (array, matrix, linked list, function, string)

干货 | 新手经常忽略的嵌入式基础知识点,你都掌握了吗?

通过SCCM SQL生成计算机上一次登录用户账户报告

A detailed explanation of the implementation principle of go Distributed Link Tracking

starring开发HttpJson接入点+数据库
随机推荐
电源噪声分析
flink cdc全量读mysql老是报这个错怎么处理
Ask a question. Adbhi supports the retention of 100 databases with the latest IDs. Is this an operation like this
应用程序DDoS攻击原理及防御方法
假如,程序员面试的时候说真话
ArrayList源码解析
我链接mysql 报这个错 是啥意思呀?
请教一个问题。adbhi支持保留一个ID最新100条数据库,类似这样的操作吗
电源效率测试
UnityShader 世界坐标不随模型变化
Introduction and download tutorial of two types of soil data
Why are life science enterprises on the cloud in succession?
微信小程序轮播图怎么自定义光标位置
华为机器学习服务语音识别功能,让应用绘“声”绘色
PLC功能块系列之多段曲线控温FB(SCL程序)
Knowledge points in T-SQL
Multi segment curve temperature control FB (SCL program) of PLC function block series
1: Mosaic of 100W basic geographic information data
小白请教下各位大佬,cdc抽取mysql binlog是严格顺序的吗
Value passing and reference passing of value types and reference types in CSharp