问题
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?
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.
回答1:
Ip address could be checked any where, but if require to get before Passport need middleware:
create app/Http/Middleware/IpMiddleware.php class
<?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);
}
}
in app/Http/Kernel.php add 'ip' => \App\Http\Middleware\IpMiddleware::class,
protected $routeMiddleware = [
'ip' => \App\Http\Middleware\IpMiddleware::class,
];
in routes/web.php
Route::group(['middleware' => ['ip', 'auth:api']], function () {
//your routes
});
回答2:
I suggest you use a middleware, and in that middleware add a new variable to session info:
public function handle(Request $request)
{
$request->session()->set('initial_ip', $request->ip());
return $next(...);
}
after that, you can just fetch this value from session anywhere in the code, and compare it with the current $request->ip() value.
来源:https://stackoverflow.com/questions/53632114/laravel-passport-how-to-validate-client-ip-when-requesting-api