コンテンツにスキップ

BasicAuthミドルウェアの使用

GinにはHTTP基本認証を実装する組み込みのgin.BasicAuth()ミドルウェアが付属しています。ユーザー名/パスワードのペアのgin.Accountsマップ(map[string]stringのショートカット)を受け取り、適用されたルートグループを保護します。

package main
import (
"net/http"
"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() {
router := gin.Default()
// gin.BasicAuth()ミドルウェアを使用したグループ
// gin.Accountsはmap[string]stringのショートカット
authorized := router.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(http.StatusOK, gin.H{"user": user, "secret": secret})
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
}
})
// 0.0.0.0:8080でリッスンしてサーブ
router.Run(":8080")
}

テスト

curlの-uフラグを使用して基本認証の資格情報を提供します:

Terminal window
# 認証成功
curl -u foo:bar http://localhost:8080/admin/secrets
# => {"secret":{"email":"[email protected]","phone":"123433"},"user":"foo"}
# パスワード不正 -- 401 Unauthorizedを返す
curl -u foo:wrongpassword http://localhost:8080/admin/secrets
# 資格情報なし -- 401 Unauthorizedを返す
curl http://localhost:8080/admin/secrets