camposer 安装Jwt类 composer require firebase/PHP-jwt 2.在App文件下新建Services文件夹,新建JwtServicer类 3.类中写入以下代码 use Firebase\JWT\JWT;
camposer 安装Jwt类
composer require firebase/PHP-jwt
2.在App文件下新建Services文件夹,新建JwtServicer类
3.类中写入以下代码
use Firebase\JWT\JWT;
use Firebase\JWT\Key
public static function createToken($userId)
{
$key = "example_key";
$payload = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000,
'user_id'=>$userId
);
$jwt = JWT::encode($payload, $key, 'HS256');
return $jwt;
}
public static function decodeToken($jwt){
$key = "example_key";
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
if ($decoded){
return $decoded;
}else{
return false;
}
}
4.新建中间件
php artisan make:middleware CheckapiLogin
5.在中间件中写入 ,将token放入header中传输
public function handle(Request $request, Closure $next)
{
//将token放入header中传输
$token=$request->header('token');
if (!$token){
return response()->json(['code'=>500,'msg'=>'token不存在','data'=>[]]);
}
$userId=JwtServer::decodeToken($token);
if ($userId){
//将加密id解密传入下一步
$request->attributes->add(['user_id'=>$userId->user_id]);
}else{
return response()->json(['code'=>500,'msg'=>'token过期','data'=>[]]);
}
return $next($request);
}
6.路由直接调用中间件
7.控制器获取token解密的凭证
$userId=$request->get('user_id');
8.前端在header 中调用
来源地址:https://blog.csdn.net/m0_58861359/article/details/128496606
--结束END--
本文标题: php firebase/php-jwt
本文链接: https://lsjlt.com/news/385048.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0