PHP-JWT使用教程
官方使用教程firebase/php-jwt - Packagist
Installation
Use composer to manage your dependencies and download PHP-JWT:
1
| composer require firebase/php-jwt
|
Optionally, install the paragonie/sodium_compat
package from composer if your php is < 7.2 or does not have libsodium installed:
1
| composer require paragonie/sodium_compat
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| use Firebase\JWT\JWT;
class compareToken { public function signToken ($uid) { $key = 'example_key'; $payload = [ 'iss' => 'http://example.org', 'aud' => 'http://example.com', 'iat' => time(), 'nbf' => time(), "exp" => time() + 200, "data"=> [ 'uid'=>$uid ] ]; $jwt = JWT::encode($payload, $key, "HS256"); return $jwt } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| use Firebase\JWT\JWT; use Firebase\JWT\Key;
class compareToken { public function handle ($request, \Closure $next) { $token = request()->header('token'); if (!isset($token) || empty($token)) { return json(['code'=>400,'message'=>'token不存在']); } $jwt = JWT::decode($token,new Key('example_key','HS256')); if($jwt){ return $next($request); };
} }
|
分隔符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| namespace app\admin\controller;
use app\BaseController; use Firebase\JWT\JWT; use Firebase\JWT\Key; use think\App;
class Base extends BaseController { public function __construct(App $app) { parent::__construct($app); $token = request()->header('Authorization'); $jwt = JWT::decode($token,new Key('admin_key','HS256'));
if($jwt){ $this->id = $jwt->data->id; $this->username = $jwt->data->username; }; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| namespace app\admin\controller; class Index extends Base { public function demo(){ $id = $this->id; $username = $this->usernmae; echo $id; echo $username; } }
|
Author: Linyin
Permalink: https://linyin022.github.io/posts/552050446.html
License: Copyright (c) 2019 CC-BY-NC-4.0 LICENSE