Home > Article > Backend Development > Full record of the actual simulation process of JWT login authentication
After careful compilation by php editor Banana, we introduce to you a popular full record of the actual development simulation process - JWT login authentication actual simulation. JWT (JSON Web Token) is an open standard for authentication. It generates a token (Token) after the user successfully logs in, and the user carries this token in subsequent requests for identity authentication. This article will provide an in-depth analysis of the implementation process of JWT login authentication and provide a comprehensive practical demonstration recording. In the process, we will take you to understand the principles of JWT and how to apply it in actual development. Whether you are a beginner or an experienced developer, you can gain valuable knowledge and practical experience from this article.
The server verifies the validity of the token and returns the response data only after passing the request
Token authentication advantages
? Header/header
header
consists of two parts: The type of token
JWT
and algorithmname:H<strong class="keylink">Mac</strong>
,SHA256
,RSA
{ "alg": "HS256", "typ": "JWT" }
? Payload/Payload
##Payload part is also a
js<strong class="keylink">ON </strong> Object, used to store the actual data that needs to be transferred.
JWT Specifies seven default fields to choose from.
iss: Issuerexp: expiration time
sub: topic
aud: user
nbf: not available before
iat: publication time
jti: JWT ID used to identify this JWT
{ "iss": "xxxxxxx", "sub": "xxxxxxx", "aud": "xxxxxxx", "user": [ 'username': '极客飞兔', 'gender': 1, 'nickname': '飞兔小哥' ] }
// 其中secret 是密钥 String signature = HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
fetch('license/login', { headers: { 'Authorization': 'X-TOKEN' + token } })
ThinkPHP<strong class="keylink">6</strong>Integration
JWT Login authentication for actual simulation
Install JWT extension
composer require firebase/php-jwt
Encapsulation to generate JWT and decryption method
<?php namespace app\services; use app\Helper; use Firebase\JWT\JWT; use Firebase\JWT\Key; class JwtService { protected $salt; public function __construct() { //从配置信息这种或取唯一字符串,你可以随便写比如md5('token') $this->salt = config('jwt.salt') || "autofelix"; } // jwt生成 public function generateToken($user) { $data = array( "iss" => 'autofelix',//签发者 可以为空 "aud" => 'autofelix', //面象的用户,可以为空 "iat" => Helper::getTimestamp(), //签发时间 "nbf" => Helper::getTimestamp(), //立马生效 "exp" => Helper::getTimestamp() + 7200, //token 过期时间 两小时 "user" => [ // 记录用户信息 'id' => $user->id, 'username' => $user->username, 'truename' => $user->truename, 'phone' => $user->phone, 'email' => $user->email, 'role_id' => $user->role_id ] ); $jwt = JWT::encode($data, md5($this->salt), 'HS256'); return $jwt; } // jwt解密 public function chekToken($token) { JWT::$leeway = 60; //当前时间减去60,把时间留点余地 $decoded = JWT::decode($token, new Key(md5($this->salt), 'HS256')); return $decoded; } }
After the user logs in, a JWT identification is generated
<?php declare (strict_types=1); namespace app\controller; use think\Request; use app\ResponseCode; use app\Helper; use app\model\User as UserModel; use app\services\JwtService; class License { public function login(Request $request) { $data = $request->only(['username', 'passWord', 'code']); // ....进行验证的相关逻辑... $user = UserModel::where('username', $data['username'])->find(); // 验证通过生成 JWT, 返回给前端保存 $token = (new JwtService())->generateToken($user); return json([ 'code' => ResponseCode::SUCCESS, 'message' => '登录成功', 'data' => [ 'token' => $token ] ]); } }
Middleware verifies whether the user is logged in
Registermiddleware in middleware.php
##
<?php // 全局中间件定义文件 return [ // ...其他中间件 // JWT验证 \app\middleware\Auth::class ];After registering the middleware, improve the verification logic in the authority verification middleware
<?php declare (strict_types=1); namespace app\middleware; use app\ResponseCode; use app\services\JwtService; class Auth { private $router_white_list = ['login']; public function handle($request, \Closure $next) { if (!in_array($request->pathinfo(), $this->router_white_list)) { $token = $request->header('token'); try { // jwt 验证 $jwt = (new JwtService())->chekToken($token); } catch (\Throwable $e) { return json([ 'code' => ResponseCode::ERROR, 'msg' => 'Token验证失败' ]); } $request->user = $jwt->user; } return $next($request); } }
总而言之,如果使用了分布式,切只能在session和jwt里面选的时候,就一定要选jwt。
The above is the detailed content of Full record of the actual simulation process of JWT login authentication. For more information, please follow other related articles on the PHP Chinese website!