【问题标题】:Access public Laravel API only from certain server IP?仅从特定服务器 IP 访问公共 Laravel API?
【发布时间】:2021-03-02 08:28:50
【问题描述】:

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

API 路由如下:

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

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

【问题讨论】:

标签: laravel api


【解决方案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);
    }

}

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

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

然后在你的路由上设置中间件:

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

【讨论】:

    【解决方案2】:

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

    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)配对

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多