token的使用
tp6实现JWT
composer安装JWT
1
| composer require firebase/php-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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| use Firebase\JWT\JWT; use Firebase\JWT\Key;
class Test { private $key = 'example_key'; public function generate($userId){ $payload = [ 'iss' => 'http://example.org', 'aud' => 'http://example.com', 'exp' => time()+3600*2, 'iat' => time(), 'nbf' => time(), 'data' => [ 'userId' => $userId ] ];
$token = JWT::encode($payload, $this->key, 'HS256'); return $token; }
public function parse($token){ $decoded = JWT::decode($token, new Key($this->key, 'HS256'));
return $decoded->data->userId; }
public function authToken(){ $createToken = $this->generate('zhangs'); echo $createToken; echo '<br>'; $token = Request::get('token');
echo $this->parse($token); } }
|
解决跨域
tp6解决跨域,在middleware.php中配置
1 2
| \think\middleware\AllowCrossDomain::class,
|
首次请求生成token和设置token
前端代码
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 26 27 28 29 30 31 32 33 34
| const data = JSON.stringify({ userAccount: 91222, password: 'swp' });
let token = localStorage.getItem('token')
fetch('http://www.sunwp.com/sunwp_forum/test/test',{ method:"POST", body:data, headers:{ 'Content-Type': 'application/json', 'Authorization': `${token}`, } }).then(response => response.json()) .then(data => { console.log('获取的数据',data) return data }) .then(res=>{ let token = res.token localStorage.setItem('token',token) console.log('已将token存放到local storage中') }) .catch((error)=>{ console.log('Error',error) })
|
后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public function test(){ $userAccount = Request::param('userAccount'); $password = Request::param('password'); $token = null; if($userAccount == '91222'){ $status = 0; if($password == 'swp'){ $status = 1; $token = $this->generate($userAccount); } }else{ $status = 0; } $data = ['msg'=>'返回的信息','status'=>$status,'token'=>$token]; return json($data); }
|
非首次请求设置请求头和获取请求头
前端
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let token = localStorage.getItem('token')
fetch('http://www.sunwp.com/sunwp_forum/test/test2',{ method:"GET", headers:{ 'Content-Type': 'application/json', 'Authorization': `${token}`, } }).then(response => response.json()) .then(res=>{ console.log(res) })
|
tp6
1 2 3 4 5 6 7 8
| public function test2(){ $header = Request::header('Authorization'); $param = $this->parse($header);
$data = ['msg'=>'用户信息','data'=>$param]; return json($data); }
|