-
背景
最近在對接某大廠,部署差不多了,但是在漏洞掃描環節有問題,前端是用vue代碼寫的。后端是php。發現前端路由可以攔截未登錄的url。但是后端php接口不用登錄就能訪問,很危險 -
解決方法
一、創建 Auth 中間件
首先創建一個專門用于驗證 Session 的中間件: 里面可以放開不用登錄的接口
<?php
// 目錄位置 app/middleware/Auth.php
namespace app\middleware;use think\facade\Session;
use think\Response;class Auth
{// 定義不需要驗證的接口路徑protected $exceptPaths = ['Auth/login', // 登錄接口'Auth/logout', // 注冊接口'Auth/getCode', // 注冊接口'Index/getTitle', // 注冊接口// 可添加更多無需驗證的接口...];public function handle($request, \Closure $next){// 獲取當前請求的路徑(不含域名和參數)$path = $request->pathinfo();// 檢查是否為排除的路徑if ($this->shouldPassThrough($path)) {return $next($request); // 跳過驗證,直接繼續}// 檢查Session中是否有登錄用戶信息if (!Session::has(SESSION_LOGIN_KEY)) {// 未登錄,返回JSON錯誤響應return json(['code' => 0,'msg' => '請先登錄','data' => 401,'url' => null,'wait' => 3]);}// 已登錄,將用戶信息注入請求對象,方便后續使用$request->user = Session::get(SESSION_LOGIN_KEY);// 繼續執行后續請求處理return $next($request);}// 判斷請求是否應跳過驗證protected function shouldPassThrough($path){foreach ($this->exceptPaths as $except) {if (strpos($path, $except) === 0) {return true;}}return false;}
}
二、注冊中間件
有兩種方式注冊中間件,根據你的需求選擇:
- 全局中間件(所有請求都驗證)
打開 目錄位置app/middleware.php 文件,添加中間件:
// app/middleware.php
return [// 其他中間件...\app\middleware\Auth::class,
];
- 路由中間件(按需驗證)
如果你只想驗證部分接口,在路由定義中使用中間件:
// app/route/route.php
use think\facade\Route;// 應用Auth中間件到整個Video控制器組
Route::group('video', function () {Route::get('getIqiyiLists', 'Video/getIqiyiLists');Route::get('getSohuLists', 'Video/getSohuLists');// 其他接口...
})->middleware(\app\middleware\Auth::class);// 或者只應用到特定接口
Route::get('video/getIqiyiLists', 'Video/getIqiyiLists')->middleware(\app\middleware\Auth::class);
- 總結
大概就是這樣玩的。ThinkPHP 的中間件機制還是挺不錯。后續你還可以加入權限的控制之類的。如果發現博文有問題,歡迎老鳥指點一二