Skip to content
All posts
LaravelAPISecurity

API extra security layer with Timestamp protection using Laravel

January 25, 2021·Read on Medium·

Been reading on improving Rest API security. Some idea point out that put a timestamp on every API request would be good. This will prevent very basic replay attacks from people who are trying to brute force your system without changing this timestamp.

So i came out just simple solution using Middleware to validate HTTP header request.

Specify header

Define constant what would be the HTTP header name should be send by API

const TIMESTAMP = 'X-Timestamp';

Check timestamp range

Lets say we only accept timestamp different range less than 30 seconds only

now()->diffInSeconds(Carbon::parse($timestamp)) < 30

Lastly

It would be something like this.

TimestampProtection.php View on GitHub
<?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);
    }
}

That’s it 😁. Simple solution from me. Thank for your time

Found this helpful?

If this article saved you time or solved a problem, consider supporting — it helps keep the writing going.

Originally published on Medium.

View on Medium