[接口v1]对接平台API-鉴权authtoken接口和getGameUrl接口

This commit is contained in:
2026-03-09 13:50:32 +08:00
parent a37da0b6f5
commit e726fc3041
7 changed files with 289 additions and 0 deletions

83
server/app/api/cache/AuthTokenCache.php vendored Normal file
View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace app\api\cache;
use support\think\Cache;
/**
* 平台 auth-token Redis 缓存
* 用于 /api/v1/authToken 鉴权接口颁发的 token 存储与校验
*/
class AuthTokenCache
{
private static function devicePrefix(): string
{
return config('api.auth_token_device_prefix', 'api:auth_token:');
}
private static function tokenPrefix(): string
{
return config('api.auth_token_prefix', 'api:auth_token:t:');
}
private static function expire(): int
{
return (int) config('api.auth_token_exp', 86400);
}
/**
* 存储 auth-token同一 agent_id 只保留最新一个)
* @param string $agentId 代理 ID
* @param string $token 生成的 auth-token
*/
public static function setToken(string $agentId, string $token): bool
{
if ($agentId === '' || $token === '') {
return false;
}
$exp = self::expire();
if ($exp <= 0) {
return false;
}
$oldToken = Cache::get(self::devicePrefix() . $agentId);
if ($oldToken !== null && $oldToken !== '') {
Cache::delete(self::tokenPrefix() . $oldToken);
}
Cache::set(self::tokenPrefix() . $token, $agentId, $exp);
Cache::set(self::devicePrefix() . $agentId, $token, $exp);
return true;
}
/**
* 根据 agent_id 获取当前有效的 token不存在或已过期返回 null
*/
public static function getTokenByAgentId(string $agentId): ?string
{
if ($agentId === '') {
return null;
}
$val = Cache::get(self::devicePrefix() . $agentId);
return $val !== null && $val !== '' ? (string) $val : null;
}
/**
* 根据 auth-token 获取 agent_id不存在或已过期返回 null
*/
public static function getAgentIdByToken(string $token): ?string
{
if ($token === '') {
return null;
}
$val = Cache::get(self::tokenPrefix() . $token);
return $val !== null && $val !== '' ? (string) $val : null;
}
/**
* 校验 auth-token 是否有效
*/
public static function isValidToken(string $token): bool
{
return self::getAgentIdByToken($token) !== null;
}
}

View File

@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace app\api\controller\v1;
use app\api\cache\AuthTokenCache;
use app\api\util\ReturnCode;
use plugin\saiadmin\basic\OpenController;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;
/**
* 平台鉴权接口
* 鉴权接口:/api/v1/authtoken
* GET 参数signature, secret, time, agent_id
* 签名signature = md5(agent_id.secret.time)
*/
class AuthTokenController extends OpenController
{
/**
* 获取 auth-token
* GET 参数signature, secret, time, agent_id
* 返回 authtoken后续 /api/v1/* 接口需在请求头携带 auth-token
*/
public function index(Request $request): Response
{
$agentId = trim((string) ($request->get('agent_id', '')));
$secret = trim((string) ($request->get('secret', '')));
$time = trim((string) ($request->get('time', '')));
$signature = trim((string) ($request->get('signature', '')));
if ($agentId === '' || $secret === '' || $time === '' || $signature === '') {
return $this->fail('缺少参数agent_id、secret、time、signature 不能为空', ReturnCode::PARAMS_ERROR);
}
$expectedSecret = config('api.auth_token_secret', '');
if ($expectedSecret === '') {
return $this->fail('服务端未配置 API_AUTH_TOKEN_SECRET', ReturnCode::SERVER_ERROR);
}
if ($secret !== $expectedSecret) {
return $this->fail('密钥错误', ReturnCode::FORBIDDEN);
}
$timeVal = (int) $time;
$tolerance = (int) config('api.auth_token_time_tolerance', 300);
$now = time();
if ($timeVal < $now - $tolerance || $timeVal > $now + $tolerance) {
return $this->fail('时间戳已过期或无效,请同步时间', ReturnCode::FORBIDDEN);
}
$expectedSignature = md5($agentId . $secret . $time);
if ($signature !== $expectedSignature) {
return $this->fail('签名验证失败', ReturnCode::FORBIDDEN);
}
$exp = (int) config('api.auth_token_exp', 86400);
$tokenResult = JwtToken::generateToken([
'id' => 0,
'agent_id' => $agentId,
'plat' => 'api_auth_token',
'access_exp' => $exp,
]);
$token = $tokenResult['access_token'];
if (!AuthTokenCache::setToken($agentId, $token)) {
return $this->fail('生成 token 失败', ReturnCode::SERVER_ERROR);
}
return $this->success([
'authtoken' => $token,
]);
}
}

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace app\api\controller\v1;
use app\api\logic\UserLogic;
use app\api\util\ReturnCode;
use plugin\saiadmin\basic\OpenController;
use support\Request;
use support\Response;
/**
* 平台 v1 游戏接口
* 获取进入游戏:/api/v1/getGameUrl
* 请求头auth-token
* POST 参数username, password默认123456, time
*/
class GameController extends OpenController
{
/**
* 获取游戏地址
* 根据 username 创建登录 tokenJWT拼接游戏地址返回
*/
public function getGameUrl(Request $request): Response
{
$username = trim((string) ($request->post('username', '')));
$password = trim((string) ($request->post('password', '123456')));
$time = trim((string) ($request->post('time', '')));
if ($username === '') {
return $this->fail('username 不能为空', ReturnCode::PARAMS_ERROR);
}
if ($password === '') {
$password = '123456';
}
if ($time === '') {
$time = (string) time();
}
try {
$logic = new UserLogic();
$result = $logic->loginByUsername($username, $password, 'chs', 0.0, $time);
} catch (\plugin\saiadmin\exception\ApiException $e) {
return $this->fail($e->getMessage(), ReturnCode::PARAMS_ERROR);
}
$gameUrlBase = rtrim(config('api.game_url', 'dice-game.yuliao666.top'), '/');
$tokenInUrl = str_replace('%3D', '=', urlencode($result['token']));
$url = $gameUrlBase . '/?token=' . $tokenInUrl;
return $this->success([
'url' => $url,
]);
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace app\api\middleware;
use app\api\cache\AuthTokenCache;
use app\api\util\ReturnCode;
use plugin\saiadmin\exception\ApiException;
use Tinywan\Jwt\JwtToken;
use Tinywan\Jwt\Exception\JwtTokenException;
use Tinywan\Jwt\Exception\JwtTokenExpiredException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 校验 auth-token 请求头JWT
* 用于 /api/v1/* 接口(除 /api/v1/authtoken 外)
* 请求头需携带 auth-token通过后注入 request->agent_id
*/
class AuthTokenMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$token = $request->header('auth-token');
$token = $token !== null ? trim((string) $token) : '';
if ($token === '') {
throw new ApiException('请携带 auth-token', ReturnCode::UNAUTHORIZED);
}
try {
$decoded = JwtToken::verify(1, $token);
} catch (JwtTokenExpiredException $e) {
throw new ApiException('auth-token 已过期', ReturnCode::TOKEN_INVALID);
} catch (JwtTokenException $e) {
throw new ApiException('auth-token 无效', ReturnCode::TOKEN_INVALID);
} catch (\Throwable $e) {
throw new ApiException('auth-token 格式无效', ReturnCode::TOKEN_INVALID);
}
$extend = $decoded['extend'] ?? [];
if ((string) ($extend['plat'] ?? '') !== 'api_auth_token') {
throw new ApiException('auth-token 无效', ReturnCode::TOKEN_INVALID);
}
$agentId = trim((string) ($extend['agent_id'] ?? ''));
if ($agentId === '') {
throw new ApiException('auth-token 无效', ReturnCode::TOKEN_INVALID);
}
$currentToken = AuthTokenCache::getTokenByAgentId($agentId);
if ($currentToken === null || $currentToken !== $token) {
throw new ApiException('auth-token 无效或已失效', ReturnCode::TOKEN_INVALID);
}
$request->agent_id = $agentId;
return $handler($request);
}
}