81 lines
2.3 KiB
PHP
81 lines
2.3 KiB
PHP
<?php
|
||
/*
|
||
* description:
|
||
* author:wh
|
||
* 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:默认鉴权
|
||
* author:wh
|
||
* @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;
|
||
}
|
||
|
||
} |