Skip to main content

Limit Login to Certain IP Addresses

By default, BookStack does not have built-in support for limiting access to the login page.

However, through BookStack's Logical Theme System (https://github.com/BookStackApp/BookStack/blob/development/dev/docs/logical-theme-system.md), it is possible to create a simple PHP code file to do a simple IP restriction.

Navigate to the BookStack directory, and find the themes/ folder. This folder should already exist by default.

Screenshot 2022-11-10 231101.png

Go into the themes folder, and create a new custom directory. You can call the folder custom.

sudo mkdir custom

Screenshot 2022-11-10 231442.png

Create a new .php file, and paste the following code into it. Modify the allowedIPs section to suit your allow IP addresses.

Screenshot 2022-11-10 231651.png

<?php

use BookStack\Facades\Theme;
use BookStack\Theming\ThemeEvents;
use Illuminate\Http\Request;

// Register a new web-middleware-before hook
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, function (Request $request) {

    // A list of IP Addresses that are allowed to use the login endpoints.
  	// IP Addresses needs to be an exact match. Wildcards are not supported in this code
    $allowedIps = [
        '127.0.0.1','192.168.1.100','10.0.0.100','172.16.1.100',
    ];

    // The endpoint prefixes to protect.
    $protectedEndpointPrefixes = [
        'login',
        'password',
    ];

    // Gather the path and IP of the current request
    $path = $request->path();
    $ip = $request->ip();

    // Redirect to home if we're requesting a protected endpoint and the user
    // IP is not within our allowed list.
    foreach ($protectedEndpointPrefixes as $endpointPrefix) {
        if (strpos($path, $endpointPrefix) === 0 && !in_array($ip, $allowedIps)) {
            return redirect('/');
        }
    }

    // Otherwise return null to tell BookStack to continue its normal behaviour.
    return null;
});

Modify your .env file, and add the name of the custom folder to APP_THEME.

Screenshot 2022-11-10 231844.png

Now when you go to BookStack's Login page, any IP that are not in the allowed IP list will get automatically redirected to the BookStack home page instead.

As always, security is best done in layers. The above code is one additional ways to secure a public-facing BookStack instance's login page, in addition to having Multi-Factor Authentication turned on.