Skip to content

Commit

Permalink
JWT token IP restriction
Browse files Browse the repository at this point in the history
  • Loading branch information
JhumanJ committed Jan 9, 2024
1 parent 0809200 commit dd83528
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
2 changes: 2 additions & 0 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http;

use App\Http\Middleware\AuthenticateJWT;
use App\Http\Middleware\CustomDomainRestriction;
use App\Http\Middleware\EmbeddableForms;
use App\Http\Middleware\IsAdmin;
Expand All @@ -27,6 +28,7 @@ class Kernel extends HttpKernel
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\SetLocale::class,
AuthenticateJWT::class,
CustomDomainRestriction::class,
];

Expand Down
46 changes: 46 additions & 0 deletions app/Http/Middleware/AuthenticateJWT.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthenticateJWT
{

/**
* Verifies the JWT token and validates the IP and User Agent
* Invalidates token otherwise
*/
public function handle(Request $request, Closure $next)
{
// Parse JWT Payload
try {
$payload = \JWTAuth::parseToken()->getPayload();
} catch (JWTException $e) {
return $next($request);
}

// Validate IP and User Agent
if ($payload) {
$error = null;
if (!\Hash::check($request->ip(), $payload->get('ip'))) {
$error = 'Origin IP is invalid';
}

if (!\Hash::check($request->userAgent(), $payload->get('ua'))) {
$error = 'Origin User Agent is invalid';
}

if ($error) {
auth()->invalidate();
return response()->json([
'message' => $error
], 403);
}
}

return $next($request);
}
}
5 changes: 4 additions & 1 deletion app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,10 @@ public function getJWTIdentifier()
*/
public function getJWTCustomClaims()
{
return [];
return [
'ip' => \Hash::make(request()->ip()),
'ua' => \Hash::make(request()->userAgent()),
];
}

public function getIsRiskyAttribute()
Expand Down

0 comments on commit dd83528

Please sign in to comment.