Gin Framework – Part 9

What is BasicAuth?

It is an open platform authentication method, which means you need to enter a username and password before accessing a restricted part of a software application or system.

Use in single route

If you need to use it for a single route, BasicAuth can register the middleware in the single route.

Code

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

// Use BasicAuth middleware
func main() {
	engine := gin.Default()
	// Set account and password, key: represents account, value: represents password
	ginAccounts := gin.Accounts{
		"user": "password",
		"abc":  "123",
	}
	// Register routes and middleware
	engine.GET("/test", gin.BasicAuth(ginAccounts), func(context *gin.Context) {
		// Get middleware BasicAuth
		user := context.MustGet(gin.AuthUserKey).(string)
		fmt.Println(user)
		context.JSON(200, gin.H{"msg": "success"})
	})
	_ = engine.Run(":9090")
}

Access effect

Hori Systems – Go Gin Framework – Part 9 – BasicAuth

Use in routing group

In most cases, we use BasicAuth middleware in routing groups.

Code

func RunUseBasicAuthWithGroup() {
	engine := gin.Default()
	// Register routing group and middleware
	userGroup := engine.Group("/user", gin.BasicAuth(gin.Accounts{
		"abc": "123",
	}))
	userGroup.GET("info", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "user.info"})
	})
}

The access effect is the same as above.