首页 > 解决方案 > 仅从特定服务器 IP 访问公共 Laravel API?

问题描述

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

API 路由如下:

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

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

标签: laravelapi

解决方案


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

首先创建它:

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,
];

然后在您的路线上设置 middelware:

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

推荐阅读