config/Sign.php
<?php
return [
'sign_ttl' => env('SIGN_TTL', 600),
'sign_type_xxx' => 'xxx',
'sign_type_test' => 'test',
'sign_type_secret' => [
'xxx' => env('SIGN_SECRET_XXX', 'test_123456'),
'test' => env('SIGN_SECRET_TEST', 'test_123456'),
],
];
app/Services/AuthSign.php
<?php
namespace App\Services;
class AuthSign
{
public static function checkSign(string $signType, string $sign, int $requestTime): array
{
$signSecret = config('sign.sign_type_secret')[$signType] ?? '';
if ($signSecret == '') {
return ['result' => false, 'msg' => '該簽名型別還沒配置'];
}
if ($sign != md5("{$requestTime}-{$signType}-{$signSecret}")) {
return ['result' => false, 'msg' => '簽名有誤'];
}
$currentTime = time();
if ($currentTime < $requestTime || ($currentTime-$requestTime) > config('sign.sign_ttl')) {
return ['result' => false, 'msg' => '簽名已過期'];
}
return ['result' => true, 'msg' => '簽名校驗成功'];
}
public static function getSign(string $signType): array
{
$signSecret = config('sign.sign_type_secret')[$signType] ?? '';
if ($signSecret == '') {
return ['result' => false, 'msg' => '該簽名型別還沒配置'];
}
$requestTime = time();
return ['result' => true, 'time' => $requestTime, 'sign' => md5("{$requestTime}-{$signType}-{$signSecret}")];
}
}
app/Http/Middleware/AuthSignTest.php
<?php
namespace App\Http\Middleware;
use App\Facades\Response;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Closure;
class AuthSignTest
{
public function handle($request, Closure $next)
{
$sign = $request->header('sign') ?: '';
$time = $request->header('time') ? : '';
if (empty($sign) || empty($time)) {
return Response::fail('傳參有誤', [], FoundationResponse::HTTP_UNAUTHORIZED);
}
$signData = \App\Services\AuthSign::checkSign(config('sign.sign_type_test'), $sign, (int)$time);
if (!$signData['result']) {
return Response::fail("sign校驗失敗:{$signData['msg']}", [], FoundationResponse::HTTP_UNAUTHORIZED);
}
return $next($request);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結