天天看點

gin架構14--使用 BasicAuth 中間件

gin架構14--使用 BasicAuth 中間件

  • ​​介紹​​
  • ​​案例​​
  • ​​說明​​

介紹

本文主要介紹gin架構中的 basicauth 認證子產品,通過BasicAuth中間件可以快速實作 http 基礎認證,提高應用安全性。

案例

源碼

package main

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

// 模拟一些私人資料
var secrets = gin.H{
    "foo":    gin.H{"email": "[email protected]", "phone": "123433"},
    "austin": gin.H{"email": "[email protected]", "phone": "666"},
    "lena":   gin.H{"email": "[email protected]", "phone": "523443"},
}

func main() {
    r := gin.Default()
    // 路由組使用 gin.BasicAuth() 中間件
    // gin.Accounts 是 map[string]string 的一種快捷方式
    authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
        "foo":    "bar",
        "austin": "1234",
        "lena":   "hello2",
        "manu":   "4321",
    }))
    // /admin/secrets 端點
    // 觸發 "localhost:8080/admin/secrets
    authorized.GET("/secrets", func(c *gin.Context) {
        // 擷取使用者,它是由 BasicAuth 中間件設定的
        user := c.MustGet(gin.AuthUserKey).(string)
        if secret, ok := secrets[user]; ok {
            c.JSON(200, gin.H{
                "user":   user,
                "secret": secret,
            })
        } else {
            c.JSON(200, gin.H{
                "user":   user,
                "secret": "No Secret",
            })
        }
    })
    r.Run(":8080")
}      
http://127.0.0.1:8080/admin/secrets
# 輸出入賬号/密碼 foo/bar
{
    "secret": {
        "email": "[email protected]",
        "phone": "123433"
    },
    "user": "foo"
}      

說明