Skip to content

Instantly share code, notes, and snippets.

@brianclogan
Created August 2, 2017 02:43
Show Gist options
  • Save brianclogan/ffbddcf88cec991ab71612772dc3ffc7 to your computer and use it in GitHub Desktop.
Save brianclogan/ffbddcf88cec991ab71612772dc3ffc7 to your computer and use it in GitHub Desktop.
Laravel Horizon - Authorizing Access via IP Addresses on Production Environments

So, with Laravel Horizon here, I ventured to use it. I found something though, it is possible, but VERY difficult to get the current user in the App Service Provider.

I set out a different route, using IP Addresses.

Since our office has a static IP, I modified the following:

.env - Adding the remote addresses as a JSON encoded array to a new variable

REMOTE_ADDRESSES='["xxx.xxx.xxx.xxx"]'

AppServiceProvider.php - Added logic in that will check the remote address against the array, if it is found, they get in.

Horizon::auth(function ($request) {
  $address = $request->server->get('REMOTE_ADDR');
  $allowed_addresses = json_decode(env('REMOTE_ADDRESSES'));
  return (in_array($address, $allowed_addresses));
});

This allowed me to in the production enviorment, still view all of the queues and supervisors running across now 3 servers, 2 in the US, and 1 in the EU.

I just have to say, @taylorotwell, THANK YOU for this. I have been building my own every time for some type of interface that would do this, but this, is 100000x better.

@dallin
Copy link

dallin commented Oct 24, 2022

For anyone stumbling across this, I was able to accomplish this with the gate() function in HorizonServiceProvider.php:

    protected function gate()
    {
        Gate::define('viewHorizon', function ($user = null) {
            $allowed_addresses = json_decode(env('REMOTE_ADDRESSES'));
            return in_array(request()->ip(), $allowed_addresses);
        });
    }

Take note of $user = null as described in the Laravel Docs here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment