Home >Backend Development >PHP Tutorial >What is JWT? A brief understanding of JWT
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!