Files
fast_response/admin/application/api/controller/BaseApiAuthController.php
2025-03-25 13:47:17 +08:00

81 lines
2.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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;
}
}