Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

meeshka's avatar

Allowing only few IPs to acces API

I'm creating an api for internal usage. I would like to restrict access to this api which has the prefix Xapi/v1/. Is there a simple and safer way to achieve this like using a middleware? e.g I just need 10.11.3.* IPs to be able to access this.

0 likes
7 replies
bobbybouwmann's avatar

Just create a middleware and check if the ip address matches

<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\IpUtils;

class RedirectInvalidIPs
{
    protected $ips = [
        '65.202.143.122',
        '148.185.163.203'
    ];

    protected $ipRanges = [
        '10.11.3.1',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach ($request->getClientIps() as $ip) {
            if (! $this->isValidIp($ip) && ! $this->isValidIpRange($ip)) {
                return redirect('/');
            }
        }

        return $next($request);
    }

    protected function isValidIp($ip)
    {
        return in_array($ip, $this->ips);
    }

    protected function isValidIpRange($ip)
    {
        return IpUtils::checkIp($ip, $this->ipRanges);
    }
}

Note: I didn't tested this, I wrote it out of my head. It should head you in the right direction ;)

3 likes
meeshka's avatar

@bobbybouwmann Thanks. I'm going to try this. However, one thing I noticed (as we use CloudFlare) $request->ip() and/or $request->ips() is not listing the HTTP_X_FORWARDED_FOR. But, $request->server() lists it. Shouldn't ips() be including this as well?

meeshka's avatar

@Hamelraj I'll have two-layers of checks. One at web server level like boynet suggested and then a middleware. Doing it at web-server level is ideal.

I'll update this thread once I've a working solution. Thanks.

1 like
meeshka's avatar

Update: It's definitely getting complicated with CloudFlare around (reverse proxy). To really configure nginx to identify CloudFlare IPs, there is no real dynamic way except manually updating their ip list.

So, here is what I'm trying

  1. Ensure requests are coming to domain i.e via server_name (that indicates it's routed via CloudFlare)
  2. Then look for X-Forwarded-For header

@bobbybouwmann as far as Laravel ($request->ips()) not showing the CloudFlare IP, it seems it'll only fetch trusted proxies. Symfony has a way to configure this within Front-Controller and not sure how this can be done in Laravel. So, research continues. Any insights into this will be great.

1 like

Please or to participate in this conversation.