?
Encapsulation to generate JWT and decryption method
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
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
Register
middleware inmiddleware.php
##
After registering the middleware, improve the verification logic in the authority verification middleware
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); } }
附:为什么使用jwt而不使用session
- session是将客户端数据储存在服务器的内存,当客服端的数据过多,服务器的内存开销大;
- session的数据储存在某台服务器,在分布式的项目中无法做到共享;
- jwt的安全性更好。
总而言之,如果使用了分布式,切只能在session和jwt里面选的时候,就一定要选jwt。