gin框架-中间件gin.BasicAuth()
gin.BasicAuth
gin.BasicAuth 是一个简单的HTTP基础认证的中间件,它提供了一个非常简单的方式来保护你的路由
代码示例
func main() {
router := gin.Default()
router.Use(gin.BasicAuth(gin.Accounts{"root": "root"}))
router.GET("/hello", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "hello",
})
})
router.Run(":80")
}
疑惑
在使用中间件gin.BasicAuth()的前提下浏览器访问后端API,前端页面会弹出一个对话框,提示用户输入用户名和密码。
解惑
前端 HTTP响应信息
状态代码 401 Unauthorized
表示未经授权的请求,意味着请求需要进行身份验证或凭证认证,但是该请求发送的身份验证凭证无效或缺失,因此服务器无法授权访问所请求的资源。(浏览器访问/hello接口未携带身份信息)
WWW-Authenticate: Basic realm=”Authorization Required”
在HTTP协议中,WWW-Authenticate是一个响应头,用于指示客户端必须对自己进行认证。这个头字段通常出现在服务器返回401 Unauthorized状态码的响应中,表示请求的资源需要用户认证。
WWW-Authenticate头字段的值包含一个或多个挑战(challenge),指示了客户端必须采用哪种认证方案(scheme)并提供哪些参数。
在WWW-Authenticate: Basic realm="Authorization Required"中:
Basic表示认证方案是HTTP基本认证。在这种方案下,客户端需要提供一个用户名和密码,这两个值通过一个冒号(:)连接,然后进行Base64编码,放在Authorization请求头字段中。注意,虽然经过了Base64编码,但用户名和密码本质上仍是明文,可以轻易解码,因此这种方案并不安全。realm="Authorization Required"表示认证的领域或保护空间。realm参数的值是一个字符串,通常会显示在浏览器的认证对话框中,作为提示信息。同一服务器上可以有多个不同的realm,每个realm对应一组用户名和密码。
因此,当浏览器收到WWW-Authenticate: Basic realm="Authorization Required"响应时,它会弹出一个对话框,提示用户输入用户名和密码。用户需要提供正确的用户名和密码才能访问请求的资源。
后端
在package gin中
type Accounts map[string]string
Account是map[string]string的类型别名,在底层它们所代表的类型是相同的,都是哈希表(hash table)或字典(Dictionary),用于存储和查找相关联的字符串数据。
源代码
gin.BasicAuth()
// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
// the key is the user name and the value is the password.
func BasicAuth(accounts Accounts) HandlerFunc {
return BasicAuthForRealm(accounts, "")
}
// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
// the key is the user name and the value is the password, as well as the name of the Realm.
// If the realm is empty, "Authorization Required" will be used by default.
// (see http://tools.ietf.org/html/rfc2617#section-1.2)
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
if realm == "" {
realm = "Authorization Required"
}
realm = "Basic realm=" + strconv.Quote(realm)
pairs := processAccounts(accounts)
return func(c *Context) {
// Search user in the slice of allowed credentials
user, found := pairs.searchCredential(c.requestHeader("Authorization"))
if !found {
// Credentials doesn't match, we return 401 and abort handlers chain.
c.Header("WWW-Authenticate", realm)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using
// c.MustGet(gin.AuthUserKey).
c.Set(AuthUserKey, user)
}
}
这段代码定义了一个名为BasicAuthForRealm的函数,用于处理HTTP基础认证。这个函数需要两个参数,一个是accounts,它是一个用户名和密码的键值对集合,另一个是realm,它是一个用于展示在客户端弹出的认证框中的提示信息。
下面是对这段代码的详细解读:
首先检查
realm是否为空,如果为空,则赋予默认值"Authorization Required"。然后将
realm值附加到"Basic realm="字符串后,基本认证的WWW-Authenticate头字段格式如Basic realm="your realm"。processAccounts函数处理输入的accounts,返回一个pairs对象,它包含了用户凭证的列表。此函数返回一个Gin中间件函数,该函数将在每次请求时运行。
在中间件函数内部,首先尝试从
Authorization请求头中获取用户凭证,并在pairs列表中查找。如果没有找到匹配的凭证,那么将
WWW-Authenticate头字段设置为前面构建的realm,返回HTTP状态码401,表示认证失败,并终止后续处理。如果找到匹配的凭证,那么将用户名设置到当前请求的上下文(Context)中,并允许后续处理函数执行。这个用户名后续可以通过
c.MustGet(gin.AuthUserKey)获取。
注意,虽然这段代码可以提供基本的HTTP认证,但由于HTTP基本认证发送的是明文(虽然经过Base64编码,但可以轻易解码),所以并不安全。在生产环境中,应该考虑使用更加安全的认证方式,如HTTPS或OAuth2。
结果
后端 验证正确的用户名和密码后返回的页面
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu
推荐文章: