This commit is contained in:
2025-03-25 13:47:17 +08:00
parent 81042c384c
commit f40c0ef6e7
18 changed files with 377 additions and 32 deletions

View File

@@ -0,0 +1,81 @@
<?php
/*
* description
* authorwh
* email
* createTime{2025/3/25} {10:19}
*/
namespace app\api\controller;
use app\common\model\ApiKey;
use app\common\service\AuthService;
use think\Controller;
use think\Request;
use wanghua\general_utility_tools_php\tool\Tools;
class BaseApiAuthController extends Controller
{
public function __construct(Request $request = null)
{
parent::__construct($request);
$r = $this->requestAuth($request);
if(false === $r){
echo json_encode(['code'=>500,'msg'=>'认证失败,请重新登录']);die;
}
//if(false == $this->defaultAuth()){
// echo json_encode(['code'=>500,'msg'=>'鉴权失败,缺失必要参数']);die;
//}
}
//请求认证
function requestAuth($request){
return true;
// 获取Authorization头
$authHeader = $request->header('authorization');
if (!$authHeader) {
echo json_encode(['code' => 401, 'error' => 'Missing Authorization header']);die;
}
// 解析Bearer Token
if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
//return json(['code' => 401, 'error' => 'Invalid token format'], 401);
echo json_encode(['code' => 401, 'error' => 'Invalid token format']);die;
}
$apiKey = $matches[1];
return (new AuthService($apiKey))->verifyApiKey();
}
/**
* desc默认鉴权
* authorwh
* @return bool
*/
function defaultAuth(){
$params = input();
if(empty($params['nonce'])){
//Tools::log_to_write_txt(['服务被拒绝,鉴权参数缺失:nonce。params'=>input()]);
return false;
}
if(empty($params['timestamp'])){
//Tools::log_to_write_txt(['服务被拒绝,鉴权参数缺失:timestamp。params'=>input()]);
return false;
}
if(empty($params['sign'])){
//Tools::log_to_write_txt(['服务被拒绝,鉴权参数缺失:sign。params'=>input()]);
return false;
}
$sign = $params['sign'];
unset($params['sign']);
if(Tools::signature($params) != $sign){
//Tools::log_to_write_txt(['签名失败,服务被拒绝.'=>input()]);
return false;
}
return true;
}
}