Tech

Securing Golang Web Applications Using IP Whitelisting


In the modern realm of internet technology, the importance of ensuring the safety of web applications and servers cannot be overstated as the frequency and sophistication of cyber-attacks continue to heighten. Because of this, the necessity for robust and cutting-edge security measures for web-based systems is also on the rise.


IP address whitelisting is one of the many modern techniques for securing web applications, servers, and APIs. Although it is only used in some specific cases, it is a recommended way of ensuring restriction of access to resources on the internet when needed.


What Is IP Whitelisting?

IP whitelisting is simply a type of whitelisting that can be referred to as a web security measure used to restrict access to a network or resource to a defined IP address or range of IP addresses considered authorized to access the system.

When IP whitelisting is implemented in a system, only the IP addresses that are added to the whitelist are able to access the system and resources on it, while other IP addresses are blocked.

IP whitelisting is a very common way of securing very critical data that should be available to only an individual or a given set of people, and protected from any hacking attempt.

A common example of IP whitelisting is in MongoDB Atlas where you set up a Mongo database cluster in the cloud and you are prompted to add your current IP address to a list so that requests to your database or cluster are only allowed when they come from your computer.

When Should You Implement IP Whitelisting?

IP whitelisting isn’t something every system or application needs. There are cases where it is recommended and appropriate to implement it in an application or system. The following are some examples of scenarios where you should consider implementing an IP whitelist.

  • When the application is only intended for use by a specific group of users, such as employees or customers of a particular company.
  • When you want the application to be accessible only from a specific location, you can whitelist a range of IP addresses specific to that location only.
  • When the application is used to provide access to confidential information or intellectual property, such as a research database or proprietary software.
  • When the application is private but accessible over the internet and needs to be protected from external threats, such as DDoS attacks or malware infections.
  • When the application is hosted on a public cloud platform and needs to be protected from unauthorized access by other tenants or users of the platform.
  • When the application is used in a regulated industry, such as healthcare or finance, where compliance with security standards is required.

There are many more cases, but fundamentally, whenever an application has any of the properties stated above, then you should consider implementing an IP whitelist.

How to Implement IP Whitelisting in Go

Go is a popular modern programming language for building web servers and APIs bundled with all you need to build a standard and secure web application.

This section demonstrates the use of Go’s Gin framework to implement the sample server and IP whitelisting logic which is a middleware function. You can install the Gin framework in a project by running the following command.

 go get github.com/gin-gonic/gin

After installing the Gin framework, you may now go ahead to implement the IP whitelisting middleware. You can create a new middleware file anywhere in your project, depending on your project architecture. Here’s the implementation of the middleware function:

 package middlewares

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func IPWhiteListMiddleware(whitelist map[string]bool) gin.HandlerFunc {
    return func(c *gin.Context) {
        userIP := c.ClientIP()

        if !whitelist[userIP] {
            c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
                "error": "You are not authorized to access this resource!",
            })
        } else {
            c.Next()
        }
    }
}

In the code above, the IPWhiteListMiddleware function is defined to accept a defined IP address whitelist as an argument. The whitelist is implemented as a map data structure so that IP addresses can easily be assigned values of true and false to indicate their accessibility.

Then the function uses the Gin framework’s ClientIP function to get the current IP address of the user trying to make the request, and checks if it is present in the whitelist and with a true value. If it’s not found, or it’s found to have a value of false, the middleware aborts the request and returns a 403 error (Forbidden).

A sample endpoint to test this functionality can be implemented to see how the IP whitelist works. The following code is a program that defines a whitelist and implements two endpoints (a restricted one and an unrestricted one).

 package main

import (
    "github.com/gin-gonic/gin"
    "go-ip-whitelist/middlewares"
    "net/http"
)

var IPWhitelist = map[string]bool{
    "127.0.0.1": true,
    "111.2.3.4": true,
    "::1": true,
}

func main() {
    router := gin.Default()

    router.GET("/index", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "Welcome to my secure application!",
        })
    })

    restrictedPage := router.Group("https://www.makeuseof.com/")
    restrictedPage.Use(middlewares.IPWhiteListMiddleware(IPWhitelist))

    restrictedPage.GET("/adminZone", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "This endpoint is secured with IP whitelisting!",
        })
    })

    router.Run(":3333")
}

When the application is run with go run main.go, the server starts on port 3333, and you can run test requests to the /adminZone endpoint, to see how the middleware works. You can also toggle the value of the localhost IP in the whitelist between true and false.

Here’s a sample request to show when the IP address is not whitelisted or when its value in the whitelist is set to false:

Test request for when the IP address is not whitelisted

Here’s another request for when the IP address is present in the IP whitelist with its value set to true:

Test request for when the IP address is whitelisted

You may get a 403 error response (Forbidden) if you test the program by whitelisting the generic localhost IP address (127.0.0.1). The IP address that will most likely work locally is ::1 which is the IPv6 equivalent of 127.0.0.1 (Ipv4). Try whitelisting ::1 if 127.0.0.1 refuses to work, and you may also try to log the userIP variable in the console to see the exact address being used.

Securing Web Apps With IP Whitelisting

In today’s world, the security of web applications and systems is of utmost importance as technology keeps advancing. IP whitelisting is a very simple and effective way to restrict access to resources on the internet to only trusted sources.

So far in this article, the concept of IP address whitelisting has been covered in detail, when to implement it, and how to implement it in Go using the Gin framework. It is recommended to only implement IP whitelisting where appropriate to avoid unnecessary technical costs.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button