Skip to content

Instantly share code, notes, and snippets.

@Brymes
Last active May 9, 2023 15:32
Show Gist options
  • Save Brymes/00e51eecbe461561e6c786ba4c116d09 to your computer and use it in GitHub Desktop.
Save Brymes/00e51eecbe461561e6c786ba4c116d09 to your computer and use it in GitHub Desktop.
IP WhiteIisting with Golang(Go) Gin

IP WhiteIisting with Golang(Go) Gin

Securing endpoints to specific IP addresses to prevent unauthorized access is a common practice in Backend engineering particularly for sensitive endpoints.

An Example is Securing Webhook endpoints E.g. Paystack

The files Attached

  • main.go :: Houses the server
  • middleware.go :: Houses the IP whitelisting function

The approach is to have selected endpoints available to only selected IP addresses by taking advantage of Gin's middleware Approach

Note:

  • This example can't be tested out locally
  • Supply real IP addresses to the IpWhitelist map
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
var IPWhitelist = map[string]bool{
"52.31.139.75": true,
"1.1.1.1": true,
"2.2.2.2": true,
}
func main() {
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
protectedEndpoint := router.Group("/")
protectedEndpoint.Use(IPWhiteListMiddleware(IPWhitelist))
protectedEndpoint.GET("protectedEndpoint", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "This is a protected endpoint",
})
})
router.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func IPWhiteListMiddleware(whitelist map[string]bool) gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
if !whitelist[ip] {
c.IndentedJSON(http.StatusForbidden, gin.H{
"message": "You are not authorised to use this endpoint",
})
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment