Last active
January 25, 2021 01:04
-
-
Save afiqiqmal/ea25e966f436bdbd7fd44af6e736d555 to your computer and use it in GitHub Desktop.
API extra security layer with Timestamp protection using Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use \RuntimeException; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Carbon; | |
class TimestampProtection | |
{ | |
const TIMESTAMP = 'X-Timestamp'; | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle(Request $request, Closure $next) | |
{ | |
if (!$timestamp = $request->header(self::TIMESTAMP)) { | |
throw new \RuntimeException('Service blocked! Need to specify request timestamp header'); | |
} | |
if (now()->diffInSeconds(Carbon::parse($timestamp)) > 30) { | |
throw new \RuntimeException('Service blocked! Invalid Timestamp Synchronization'); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment