Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Created September 15, 2019 15:32
Show Gist options
  • Save sibu-github/af26043c496c1fa0a193861b71b429b6 to your computer and use it in GitHub Desktop.
Save sibu-github/af26043c496c1fa0a193861b71b429b6 to your computer and use it in GitHub Desktop.
http basic authentication with gin-gonic/gin library
package main
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func main() {
fmt.Println("main starting ...")
router := gin.Default()
router.Use(func(c *gin.Context) {
authString := c.Request.Header.Get("Authorization")
fmt.Println(authString)
auth := strings.SplitN(authString, " ", 2)
fmt.Println(auth)
if len(auth) != 2 || auth[0] != "Basic" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "Invalid auth",
})
c.Abort()
}
payload, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
}
fmt.Println(payload)
pair := strings.SplitN(string(payload), ":", 2)
fmt.Println("User ID: ", pair[0])
fmt.Println("Password: ", pair[1])
if pair[0] == "test" && pair[1] == "test" {
c.Next()
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "unauthorized",
})
c.Abort()
}
})
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
})
})
router.POST("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
})
})
router.Run(":9000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment