This article brings you what is JWT? A simple understanding of JWT has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I have never taken a good look at jwt until I had to do web verification two days ago. A friend recommended jwt to me. Only then did I discover that jwt has been widely used by everyone. It seems I'm a little out. Haha, take advantage of the world to take a good look at this.
JWT (JSON Web Token), as the name suggests, is a token that can be transmitted on the Web. This token is formatted in JSON format. It is an open source standard (RFC 7519) that defines a compact, self-contained way to securely transmit information in JSON format between different entities.Since many projects now have front-end and back-end separation, restful api mode. Therefore, the traditional session mode cannot meet the authentication requirements. At this time, the role of jwt comes. It can be said that restful api authentication is a good application scenario of jwt.
The following is a small demo
<?php require_once 'src/JWT.php'; header('Content-type:application/json'); //定义Key const KEY = 'dasjdkashdwqe1213dsfsn;p'; $user = [ 'uid'=>'dadsa-12312-vsd1s1-fsds', 'account'=>'daisc', 'password'=>'123456' ]; $redis = redis(); $action = $_GET['action']; switch ($action) { case 'login': login(); break; case 'info': info(); break; } //登陆,写入验证token function login() { global $user; $account = $_GET['account']; $pwd = $_GET['password']; $res = []; if($account==$user['account']&&$pwd==$user['password']) { unset($user['password']); $time = time(); $token = [ 'iss'=>'http://test.cc',//签发者 'iat'=>$time, 'exp'=>$time+60, 'data'=>$user ]; $jwt = \Firebase\JWT\JWT::encode($token,KEY); $res['code'] = 200; $res['message'] = '登录成功'; $res['jwt'] = $jwt; } else { $res['message']= '用户名或密码错误'; $res['code'] = 401; } exit(json_encode($res)); } function info() { $jwt = $_SERVER['HTTP_AUTHORIZATION'] ?? false; $res['code'] = 200; if($jwt) { $jwt = str_replace('Bearer ','',$jwt); if(empty($jwt)) { $res['code'] = 401; $res['msg'] = 'You do not have permission to access.'; exit(json_encode($res)); } try{ $token = (array) \Firebase\JWT\JWT::decode($jwt,KEY, ['HS256']); if($token['exp']<time()) { $res['code'] = 401; $res['msg'] = '登录超时,请重新登录'; } $res['data']= $token['data']; }catch (\Exception $E) { $res['code'] = 401; $res['msg'] = '登录超时,请重新登录.'; } } else { $res['code'] = 401; $res['msg'] = 'You do not have permission to access.'; } exit(json_encode($res)); } //连接redis function redis() { $redis = new Redis(); $redis->connect('127.0.0.1'); return $redis; }
This dmeo uses jwt to perform a simple authentication. A php-jwt encryption package is used. https://github.com/firebase/php-jwt
where KEY is the defined private key, which is the sign part in jwt. This must be saved.
The header part of the php-jwt package has been completed for us. The encryption code is as follows
*/ public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if ( isset($head) && is_array($head) ) { $header = array_merge($head, $header); } $segments = array(); $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = static::sign($signing_input, $key, $alg); $segments[] = static::urlsafeB64Encode($signature); return implode('.', $segments); }
It can be seen that the default encryption method is HS256. This is also the reason why jwt is safe. At this stage, HS256 encryption is still very secure.
This package also supports certificate encryption.
This package has completed the encryption and decryption process for us. So we only need to define the poyload part in jwt. That is the token part in the demo. If the encryption is successful, an encrypted JWT string will be obtained. The front end needs to carry this JWT string as authentication next time when requesting the API.
Add Authorization in the header. During server-side verification, this value is obtained to verify the validity of the reply.
The following are some common configurations of poyload
$token = [ #非必须。issuer 请求实体,可以是发起请求的用户的信息,也可是jwt的签发者。 "iss" => "http://example.org", #非必须。issued at。 token创建时间,unix时间戳格式 "iat" => $_SERVER['REQUEST_TIME'], #非必须。expire 指定token的生命周期。unix时间戳格式 "exp" => $_SERVER['REQUEST_TIME'] + 7200, #非必须。接收该JWT的一方。 "aud" => "http://example.com", #非必须。该JWT所面向的用户 "sub" => "jrocket@example.com", # 非必须。not before。如果当前时间在nbf里的时间之前,则Token不被接受;一般都会留一些余地,比如几分钟。 "nbf" => 1357000000, # 非必须。JWT ID。针对当前token的唯一标识 "jti" => '222we', # 自定义字段 "GivenName" => "Jonny", # 自定义字段 "name" => "Rocket", # 自定义字段 "Email" => "jrocket@example.com", ];
The configurations contained in it can be configured freely, or you can add some others by yourself. These are commonly used by everyone on the Internet, and it can be said to be a kind of agreement.
The above is the detailed content of What is JWT? A brief understanding of JWT. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
