Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active January 25, 2021 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/ea25e966f436bdbd7fd44af6e736d555 to your computer and use it in GitHub Desktop.
Save afiqiqmal/ea25e966f436bdbd7fd44af6e736d555 to your computer and use it in GitHub Desktop.
API extra security layer with Timestamp protection using Laravel
<?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