Add basic authentication to Gin web application

0
60
Add basic authentication to Gin web application
Add basic authentication to Gin web application

Like any other web framework, Gin-gonic also provides a convenient way to add basic authentication. Today, I will show you how to add basic authentication to Gin web application.

Setup Gin project

First thing to do is to setup a Gin web application to make sure you can follow along. We will create a new Gin-gonic application by issuing these commands:

$ mkdir gin-basicauth

$ cd gin-basicauth

$ go mod init petehouston.com/gin-basicauth

$ go get github.com/gin-gonic/gin

$ touch main.go

and then edit main.go with this starting piece of code:

// file: main.go
package main

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

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

	router.GET("/", func(context *gin.Context) {
		context.String(http.StatusOK, "Homepage")
	})

	router.Run()
}

To make sure it works, build and run main.go , then visit the http://127.0.0.1:8080 via browser to confirm.

$ go run main.go

Add basic authentication

To add basic authentication to our Gin application, we will use the BasicAuth() handler (middleware).

Let say we have a protected route like /admin and it is only accessible with username = admin | password = secret , we will write the code as following:

router.GET("/admin", gin.BasicAuth(gin.Accounts{
	"admin": "secret",
}), func(context *gin.Context) {
	context.String(http.StatusOK, "Welcome to admin dashboard!")
})

When there is a request coming to the /admin route, Gin will execute the chain of handlers associated with the route, and since we put the gin.BasicAuth() handler as the first handler, it will be executed first. If the authentication validation passes, the next handler, which returns the route content, will be executed. Otherwise, Gin will return default HTTP Status 401 status code as response.

You might wonder what gin.Accounts type is, well, it is actually a map[string]string:

type Accounts map[string]string

So you can put as many accounts for the basic auth as you want.

Re-run the Gin application on the browser, and visit 127.0.0.1:8080/admin URL, we expect an authentication prompt like this:

Basic Authentication Prompt
Basic Authentication Prompt

Type in the user and password defined in the code, if it matches, the page will show the admin page content, otherwise, it will return 401 and the basic authentication prompt will ask for input again.

Conclusion

That’s it, now you know how to add basic authentication to Gin web application.

Have fun!