## 一,安裝firebase/php-jwt擴展:
1,命令:
~~~
liuhongdi@lhdpc:/data/php/admapi$ composer require firebase/php-jwt
~~~
2,安裝成功后的位置:

3,查看firebase/php-jwt的版本:
~~~
liuhongdi@lhdpc:/data/php/admapi$ composer show firebase/php-jwt
~~~

## 二,前端vue代碼:
Login.vue
~~~
<template>
<div style="padding:20px;display: flex;align-items:center;justify-content: center;">
<form :model="account" style="margin-top:50px;width:400px;">
<input v-model="account.username" placeholder="請輸入用戶名" style="width:392px;font-size:16px;" /><br/>
<input v-model="account.password" type="password" placeholder="請輸入密碼" style="width:392px;margin-top:10px;font-size:16px;" /><br/>
<!--v-loading.fullscreen.lock="isLoading"-->
<div @click="login" style="margin-top:10px;width: 100%;height:40px;line-height:40px;background: #ff0000;border-radius: 10px;">
登錄
</div>
<div @click="info" style="margin-top:10px;width: 100%;height:40px;line-height:40px;background: #ff0000;border-radius: 10px;">
info
</div>
<div class="text-align-right">
</div>
</form>
</div>
</template>
<script>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { apiLogin,apiInfo,apiToken} from '@/api/api';
export default {
name: "Login",
setup() {
const accountRef = ref(null);
//表單字段
const account = reactive({
username: "",
password: "",
});
//登錄
const login = async () => {
console.log('begin login');
var data = new FormData();
data.append("username",account.username);
data.append("password",account.password);
apiLogin(data).then(res => {
//成功
if (res.code == 0) {
//保存jwt token到本地
localStorage.setItem('token', res.data.token);
//提示
ElMessage.success("登錄成功!");
} else {
ElMessage.error("登錄失敗:"+res.msg);
}
}).catch((error) => {
console.log(error)
})
};
const login2 = () => {
console.log('begin login2');
}
const info = () => {
apiInfo().then(res => {
//成功
if (res.code == 0) {
//保存jwt token到本地
//localStorage.setItem('token', res.data.token);
//提示
//ElMessage.success("登錄成功!");
console.log(res.data);
} else {
ElMessage.error("用戶信息獲取失敗:"+res.msg);
}
}).catch((error) => {
console.log(error)
})
}
return {
account,
//loginRules,
accountRef,
login,
login2,
info,
//isLoading,
};
},
}
</script>
<style scoped>
</style>
~~~
api/axios.js
```
...
//post
export function postForm (url, params) {
return new Promise((resolve, reject) => {
let headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
//判斷params中是否包含X-CSRF-TOKEN
var token = "";
if (params.has("X-CSRF-TOKEN")) {
token = params.get("X-CSRF-TOKEN");
params.delete("X-CSRF-TOKEN");
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-TOKEN': token,
}
}
_axios.post(url, params,{headers})
.then(res => {
resolve(res.data)
})
.catch(err => {
console.log("api error:");
console.log(err);
//alert(err);
reject(err.data)
})
})
}
...
```
api/api.js
```
//get,
import { get, postForm} from './axios'
//user
export const apiLogin = pLogin => postForm('/api/auth/login', pLogin)
...
```
## 三,后端php代碼:
1,創建middleware
~~~
liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckJwt
Middleware:app\middleware\CheckJwt created successfully.?
~~~
2,CheckJwt的代碼:?
~~~
<?php
declare (strict_types = 1);
namespace app\middleware;
use app\lib\util\JwtUtil;
class CheckJwt
{
/**
* 處理請求,得到用戶信息
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
$auth = $request->header('authorization');
if ($auth == null) {
return $next($request);
}
$token = str_replace("Bearer ","",$auth);
$jUtil = new JwtUtil();
$res = $jUtil->verifyjwt($token);
if (isset($res['code']) && isset($res['userId']) && $res['code'] == 0 && is_int($res['userId'])) {
$userId = $res['userId'];
$request->auth = $userId;
} else {
$request->auth = 0;
}
return $next($request);
}
}
~~~
3,app/middleware.php
使從jwt得到用戶信息的middleware生效:
~~~
<?php
// 全局中間件定義文件
return [
app\middleware\CheckJwt::class,
];
~~~
4,controller/Auth.php
~~~
<?php
declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use think\facade\Cache;
use think\Request;
use app\result\Result;
use think\response\Json;
use app\validate\Login as LoginValidate;
use app\validate\GoodsList as GoodsListValidate;
use think\exception\ValidateException;
use app\lib\util\JwtUtil;
class Auth extends BaseController
{
/*
*得到form token
*
*@return \think\Response
* */
public function token():Json {
$type="sha1";
$type = is_callable($type) ? $type : 'md5';
$token = call_user_func($type, $this->request->server('REQUEST_TIME_FLOAT'));
$key = uniqid();
Cache::set($key,$token,300);
$res = [
"token"=>$key.$token,
];
return Result::Success($res);
}
/**
* 登錄
*
* @return \think\Response
*/
public function login():Json {
// Header驗證
if ($this->request->header('X-CSRF-TOKEN')){
$reqToken = $this->request->header('X-CSRF-TOKEN');
$key = substr($reqToken,0,13);
$value = Cache::get($key);
$origToken = $key.$value;
if ($origToken === $reqToken) {
//驗證通過
} else {
//驗證不通過
return Result::Error(422,'表單token錯誤');
}
} else {
return Result::Error(423,'找不到表單token');
}
try {
validate(LoginValidate::class)
->check($_POST);
} catch (ValidateException $e) {
// 驗證失敗 輸出錯誤信息
return Result::Error(422,$e->getError());
}
if ($_POST["username"] == "dddddd" && $_POST["password"] == "111111"){
//驗證成功,生成jwt返回
$userId = 123;
$jUtil = new JwtUtil();
$token = $jUtil->createJwt($userId);
$res = ["token"=>$token];
// 防止重復提交
Cache::delete($key);
return Result::Success($res);
} else {
return Result::Error(422,"用戶名密碼錯誤");
}
}
}
~~~
Result.php
```
<?php
namespace app\result;
use think\response\Json;
class Result {
//success
static public function Success($data):Json {
$rs = [
'code'=>0,
'msg'=>"success",
'data'=>$data,
];
return json($rs);
}
//error
static public function Error($code,$msg):Json {
$rs = [
'code'=>$code,
'msg'=>$msg,
'data'=>"",
];
return json($rs);
}
}
```
5,lib/util/JwtUtil.php
~~~
<?php
namespace app\lib\util;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
class JwtUtil {
private $signKey = "lhd@2001:liuhongdi";
private $timeMinutes = 5;
/**
* 根據json web token設置的規則生成token
* @return \think\response\Json
*/
public function createJwt($userId):string
{
$key = md5($this->signKey); //jwt的簽發**,驗證token的時候需要用到
$time = time(); //簽發時間
$expire = $time + $this->timeMinutes*60; //過期時間
$token = array(
"userId" => $userId,
"iss" => "http://www.liuhongdi.com/",//簽發組織
"aud" => "lhd", //簽發作者
"iat" => $time, //簽發時間
"nbf" => $time, //生效時間
"exp" => $expire //過期時間
);
$jwt = JWT::encode($token,$key);
return $jwt;
}
/**
* 驗證token
* @return \think\response\Json
*/
public function verifyjwt($token)
{
$key = md5($this->signKey); //jwt的簽發**,驗證token的時候需要用到
try{
$jwtAuth = json_encode(JWT::decode($token,$key,array("HS256")));
$authInfo = json_decode($jwtAuth,true);
if (!$authInfo['userId']){
return ['code'=>0,'msg'=>"用戶不存在"];
}
return ['code'=>0,'userId'=>$authInfo['userId'],'msg'=>"ok"];
}catch (ExpiredException $e){
return ['code'=>0,'msg'=>"token過期"];
}catch (\Exception $e){
return ['code'=>0,'msg'=>$e->getMessage()];
}
}
}
~~~
## 四,效果測試
1,界面:用戶名 dddddd,密碼;111111,可見php的代碼:

2,未登錄時點info

3,登錄后的返回:

4,登錄后查看info的返回:

- thinkphp6執行流程(一)
- php中use關鍵字用法詳解
- Thinkphp6使用騰訊云發送短信步驟
- 路由配置
- Thinkphp6,static靜態資源訪問路徑問題
- ThinkPHP6.0+ 使用Redis 原始用法
- smarty在thinkphp6.0中的最佳實踐
- Thinkphp6.0 搜索器使用方法
- 從已有安裝包(vendor)恢復 composer.json
- tp6with的用法,表間關聯查詢
- thinkphp6.x多對多如何添加中間表限制條件
- thinkphp6 安裝JWT
- 緩存類型
- 請求信息和HTTP頭信息
- 模型事件用法
- 助手函數匯總
- tp6集成Alipay 手機和電腦端支付的方法
- thinkphp6使用jwt
- 6.0session cookie cache
- tp6筆記
- TP6(thinkphp6)隊列與延時隊列
- thinkphp6 command(自定義指令)
- command(自定義指令)
- 本地文件上傳
- 緩存
- 響應
- 公共函數配置
- 七牛云+文件上傳
- thinkphp6:訪問多個redis數據源(thinkphp6.0.5 / php 7.4.9)
- 富文本編輯器wangEditor3
- IP黑名單
- 增刪改查 +文件上傳
- workerman 定時器操作控制器的方法
- 上傳文件到阿里云oss
- 短信或者郵箱驗證碼防刷代碼
- thinkphp6:訪問redis6(thinkphp 6.0.9/php 8.0.14)
- 實現關聯多個id以逗號分開查詢數據
- thinkphp6實現郵箱注冊功能的細節和代碼(點擊鏈接激活方式)
- 用mpdf生成pdf文件(php 8.1.1 / thinkphp v6.0.10LTS )
- 生成帶logo的二維碼(php 8.1.1 / thinkphp v6.0.10LTS )
- mysql數據庫使用事務(php 8.1.1 / thinkphp v6.0.10LTS)
- 一,創建過濾IP的中間件
- 源碼解析請求流程
- 驗證碼生成
- 權限管理
- 自定義異常類
- 事件監聽event-listene
- 安裝與使用think-addons
- 事件與多應用
- Workerman 基本使用
- 查詢用戶列表按拼音字母排序
- 擴展包合集
- 查詢用戶數據,但是可以通過輸入用戶昵稱來搜索用戶同時還要統計用戶的文章和粉絲數
- 根據圖片的minetype類型獲取文件真實拓展名思路
- 到處excel
- 用imagemagick庫生成縮略圖
- 生成zip壓縮包并下載
- API 多版本控制
- 用redis+lua做限流(php 8.1.1 / thinkphp v6.0.10LTS )
- 【thinkphp6源碼分析三】 APP類之父, 容器Container類
- thinkphp6表單重復提交解決辦法
- 小程序授權
- 最簡單的thinkphp6導出Excel
- 根據訪問設備不同訪問不同模塊
- 服務系統
- 前置/后置中間件
- 給接口api做簽名驗證(php 8.1.1 / thinkphp v6.0.10LTS )
- 6實現郵箱注冊功能的細節和代碼(點擊鏈接激活方式)
- 使用前后端分離的驗證碼(thinkphp 6.0.9/php 8.0.14/vue 3.2.26)
- 前后端分離:用jwt+middleware做用戶登錄驗證(php 8.1.1 / thinkphp v6.0.10LTS )
- vue前后端分離多圖上傳
- thinkphp 分組、頁面跳轉與ajax
- thinkphp6 常用方法文檔
- 手冊里沒有的一些用法
- Swagger 3 API 注釋
- PHP 秒級定時任務
- thinkphp6集成gatewayWorker(workerman)實現實時監聽
- thinkphp6按月新增數據表
- 使用redis 實現消息隊列
- api接口 統一結果返回處理類
- 使用swoole+thinkphp6.0+redis 結合開發的登錄模塊
- 給接口api做簽名驗證
- ThinkPHP6.0 + UniApp 實現小程序的 微信登錄
- ThinkPHP6.0 + Vue + ElementUI + axios 的環境安裝到實現 CURD 操作!
- 異常$e
- 參數請求驗證自定義和異常錯誤自定義