Using BasicAuth middleware
Gin ships with a built-in gin.BasicAuth() middleware that implements HTTP Basic Authentication. It accepts a gin.Accounts map (a shortcut for map[string]string) of username/password pairs and protects any route group it is applied to.
package main
import ( "net/http"
"github.com/gin-gonic/gin")
// simulate some private datavar secrets = gin.H{}
func main() { router := gin.Default()
// Group using gin.BasicAuth() middleware // gin.Accounts is a shortcut for map[string]string authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", }))
// /admin/secrets endpoint // hit "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // get user, it was set by the BasicAuth middleware user := c.MustGet(gin.AuthUserKey).(string) if secret, ok := secrets[user]; ok { c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) } })
// Listen and serve on 0.0.0.0:8080 router.Run(":8080")}Try it
Use the -u flag with curl to supply Basic Authentication credentials:
# Successful authenticationcurl -u foo:bar http://localhost:8080/admin/secrets# => {"secret":{"email":"[email protected]","phone":"123433"},"user":"foo"}
# Wrong password -- returns 401 Unauthorizedcurl -u foo:wrongpassword http://localhost:8080/admin/secrets
# No credentials -- returns 401 Unauthorizedcurl http://localhost:8080/admin/secrets