Laravel Passport:如何在请求API时验证客户端IP

编程入门 行业动态 更新时间:2024-10-28 18:30:16
本文介绍了Laravel Passport:如何在请求API时验证客户端IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Laravel Passport作为我的API身份验证机制.一切都按预期工作,但我需要为每个请求添加一个额外的验证. 这个想法是要验证客户端IP地址以及发送到服务器的access_token.

I'm using Laravel Passport as my API authentication mechanism. Everything is working as expected, but i need to add an extra validation for each request. The idea is to validate the client IP Address alongside the access_token that is sent to the server.

有什么主意我能做到吗?

Any idea how i can accomplish this?

更新:我想检查身份验证中使用的IP(当用户登录时)是否与执行请求的IP相同.如果IP不同,则客户端必须再次登录.

UPDATE: I want to check if the IP used in the authentication (when the user logged in) is the same as the one doing the requestes. If the IP is different, the client must login again.

推荐答案

可以在任何地方检查IP地址,但是如果需要在Passport需要中间件之前获取IP地址:

Ip address could be checked any where, but if require to get before Passport need middleware:

创建 app/Http/Middleware/IpMiddleware.php 类

<?php namespace App\Http\Middleware; use Illuminate\Http\Request; class IpMiddleware { public function handle(Request $request, \Closure $next) { $ip = null; if (getenv('HTTP_CF_CONNECTING_IP')) { $ip = getenv('HTTP_CF_CONNECTING_IP'); } else if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); } else if (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } else if (getenv('HTTP_X_FORWARDED')) { $ip = getenv('HTTP_X_FORWARDED'); } else if (getenv('HTTP_FORWARDED_FOR')) { $ip = getenv('HTTP_FORWARDED_FOR'); } else if (getenv('HTTP_FORWARDED')) { $ip = getenv('HTTP_FORWARDED'); } else if (getenv('REMOTE_ADDR')) { $ip = getenv('REMOTE_ADDR'); } if (!$ip || $ip === '::1') { $ip = $request->ip(); } $ipAddress = \explode(',', $ip ?? '127.0.0.1')[0]; return $next($request); } }

在 app/Http/Kernel.php 中添加'ip'=> \ App \ Http \ Middleware \ IpMiddleware :: class,

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

在routes/web.php

Route::group(['middleware' => ['ip', 'auth:api']], function () { //your routes });

更多推荐

Laravel Passport:如何在请求API时验证客户端IP

本文发布于:2023-11-03 08:00:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   如何在   Passport   Laravel   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!