參考1. Api Authorized Signature Middleware for Laravel 5php
參考2.Laravel 5 API 服務端支持簽名受權認證laravel
以上二者內容幾一致。git
在lumen中使用github
composer require havenshen/larsign
$app->configure('larsign'); #聲明路由中間件,固然你能夠使用其餘的好比globalMiddleWare $app->routeMiddleware([ 'auth.larsign' => \HavenShen\Larsign\HandleLarsign::class, ]); $app->register(HavenShen\Larsign\LarsignServiceProvider::class); #聲明facade類 Larsign class_alias(\HavenShen\Larsign\LarsignFacade::class, 'Larsign');
#此接口須要驗籤訪問 Route::group(['middleware' => ['auth.larsign']], function () { Route::get('/larsign', function () { return [ 'message' => 'done.' ]; }); });
Route::get('/lar', function (\Illuminate\Http\Request $request) { #base64_encode會產生url不友好的符號,這裏有safebased4encode,固然就有safebased4decode #這裏臨時測試上手,找了php.net base64_encode下的評論區也有相關函數,試了不爽; #回來在larsign包check sign 扒出此部分代碼 #此方法若是客戶端也引入了larsign,能夠使用facade方式:Larsign::base64_urlSafeEncode($str) function urlsafe_b64encode($string) { $find = array('+', '/'); $replace = array('-', '_'); return str_replace($find, $replace, base64_encode($string)); } //'accessKey' => env('LARSIGN_ACCESS_KEY', 'Hi^fjhKJlIUKjuM'), // 'secretKey' => env('LARSIGN_SECRET_KEY', 'PlrNIaO'), $rawStr = "/larsign\n" . (time()+86400); //Base64 url safe encode $base64 = urlsafe_b64encode($rawStr); $sign = hash_hmac('sha1', $base64, config('larsign.secretKey'), true); $sign = urlsafe_b64encode($sign); //titching headerName Space AccessKey:sign:signingStrBase64UrlSafeEncode $headerName = config('larsign.headerName'); $accessKey = config('larsign.accessKey'); $larsignToken = "{$headerName} {$accessKey}:{$sign}:{$base64}"; //最終設置的header頭,名稱爲$headerName ;值爲$larsignToken $headerStr = $headerName . ':' . $larsignToken; dd(config('larsign'), $sign, $headerStr); });