laravel - 仅从特定服务器 IP 访问公共 Laravel API?
问题描述
我有一个现有的 Laravel 应用程序。现在,我想用 Laravel 创建另一个应用程序,使用与第一个应用程序相同的数据库,但要在自己的服务器上。
API 路由如下:
Route::apiResource('posts', PostsController::class)->only(['index', 'show']);
是否可以保护此路由并仅从新应用程序服务器的 IP 访问它?
解决方案
创建一个中间件并在您的路由中使用它。
首先创建它:
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
}]);
推荐阅读
- java - 方法返回以整数和字符串为参数的数组字符串
- spring - Spring boot Kafka - 对 Avro 对象序列化和用例的困惑
- javascript - react useMemo 是否比模块级变量更高效?
- javascript - 在单击 href 时显示文本
- c++ - 静态成员和分离线程本身的释放顺序
- javascript - 将 prop 作为字符串传递,然后将字符串转换回 javascript
- macos - 在 Python 3.9.1 中导入 SciPy 会产生 zsh: bus error; 苹果硅 M1 Mac OS 11
- google-cloud-storage - 如何强制 Google 存储文件具有“内容处置:内联”而不是“附件”?
- linux - apache 重定向 /url1/* 到 /url1/index.html
- javascript - javascript 将文档保存到 .html