Laravel Passport:如何在请求API时验证客户端IP [英] Laravel Passport: How to validate client IP when requesting API

查看:79
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆