Don40
Don40

Reputation: 417

Access public Laravel API only from certain server IP?

I have an existing Laravel application. Now, I want to create another application with Laravel, using the same database as the first app, but to be on its own server.

The API route would be like:

Route::apiResource('posts', PostsController::class)->only(['index', 'show']);

Is it possible to secure this route and access it only from the IP of the new application server?

Upvotes: 0

Views: 1559

Answers (2)

Jon White
Jon White

Reputation: 1010

There are a few available packages that provide the tools to do this for you. I've not tried any myself so I can't vouch for their quality:

https://github.com/antonioribeiro/firewall

or

https://github.com/orkhanahmadov/laravel-ip-middleware/blob/master/src/Middleware.php

I think they both achieve the primary goal by providing a Middleware that checks the IP address of the incoming request and prevents the request if address doesn't match any listed IPs.

The code, in its simplest form would be something along the lines of:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle(Request $request, Closure $next)
{
    if (in_array($request->ip(), config('ip_whitelist'))) {
        return $next($request);
    }

    abort(403);
}

Where config('ip_whitelist') returns an array of IP addresses.

I assume you would pair this with the usual API auth such as Sanctum

Upvotes: 0

mohammad asghari
mohammad asghari

Reputation: 1894

Create a middleware and use it in your route.

First create it:

php artisan make:middleware IpMiddleware

Code

<?php

namespace App\Http\Middleware;

use Closure;

class IpMiddleware
{
    
    public function handle($request, Closure $next)
    {
        if ($request->ip() != "192.168.0.155") {
        // here instead of checking a single ip address we can do collection of ips
        //address in constant file and check with in_array function
            return redirect('home');
        }

        return $next($request);
    }

}

Then add the new middleware class in the $middleware property of your app/Http/Kernel.php class.

protected $routeMiddleware = [
    //....
    'ipcheck' => \App\Http\Middleware\IpMiddleware::class,
];

Then set the middelware on your route:

Route::apiResource('posts', ['middleware' => ['ipcheck'], function () {
// your routes here
}]);

Upvotes: 2

Related Questions