仅从某些服务器 IP 访问公共 Laravel API?

时间:2021-03-02 08:28:50

标签: laravel api

我有一个现有的 Laravel 应用程序。现在,我想用 Laravel 创建另一个应用程序,使用与第一个应用程序相同的数据库,但要在自己的服务器上。

API 路由如下:

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

是否可以保护此路由并仅从新应用服务器的 IP 访问它?

2 个答案:

答案 0 :(得分:1)

创建一个中间件并在您的路由中使用它。

首先创建它:

php artisan make:middleware IpMiddleware

代码

<?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);
    }

}

然后在您的 middleware 类的 $app/Http/Kernel.php 属性中添加新的中间件类。

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

然后在您的路线上设置中间件:

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

答案 1 :(得分:0)

有一些可用的软件包可以为您提供执行此操作的工具。我自己没有尝试过,所以我不能保证它们的质量:

https://github.com/antonioribeiro/firewall

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

我认为他们都通过提供一个中间件来实现主要目标,该中间件检查传入请求的 IP 地址并在地址与任何列出的 IP 不匹配时阻止请求。

最简单形式的代码是这样的:

/**
 * 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);
}

其中 config('ip_whitelist') 返回一组 IP 地址。

我假设您会将其与常用的 API 身份验证(例如 Sanctum)配对