浏览代码

Fixes important bug in Basic Auth when using custom realm.

Manu Mtz-Almeida 10 年之前
父节点
当前提交
81b08a554e
共有 2 个文件被更改,包括 6 次插入7 次删除
  1. 4 5
      auth.go
  2. 2 2
      auth_test.go

+ 4 - 5
auth.go

@@ -7,9 +7,8 @@ package gin
 import (
 	"crypto/subtle"
 	"encoding/base64"
-	"errors"
-	"fmt"
 	"sort"
+	"strconv"
 )
 
 const (
@@ -49,15 +48,15 @@ func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
 	if realm == "" {
 		realm = "Authorization Required"
 	}
-	realm = fmt.Sprintf("Basic realm=\"%s\"", realm)
+	realm = "Basic realm=" + strconv.Quote(realm)
 	pairs := processAccounts(accounts)
 	return func(c *Context) {
 		// Search user in the slice of allowed credentials
 		user, ok := pairs.searchCredential(c.Request.Header.Get("Authorization"))
 		if !ok {
 			// Credentials doesn't match, we return 401 Unauthorized and abort request.
-			c.Writer.Header().Set("WWW-Authenticate", realm)
-			c.Fail(401, errors.New("Unauthorized"))
+			c.Header("WWW-Authenticate", realm)
+			c.AbortWithStatus(401)
 		} else {
 			// user is allowed, set UserId to key "user" in this context, the userId can be read later using
 			// c.Get(gin.AuthUserKey)

+ 2 - 2
auth_test.go

@@ -131,7 +131,7 @@ func TestBasicAuth401WithCustomRealm(t *testing.T) {
 	called := false
 	accounts := Accounts{"foo": "bar"}
 	router := New()
-	router.Use(BasicAuthForRealm(accounts, "My Custom Realm"))
+	router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\""))
 	router.GET("/login", func(c *Context) {
 		called = true
 		c.String(200, c.MustGet(AuthUserKey).(string))
@@ -144,5 +144,5 @@ func TestBasicAuth401WithCustomRealm(t *testing.T) {
 
 	assert.False(t, called)
 	assert.Equal(t, w.Code, 401)
-	assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom Realm\"")
+	assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom \\\"Realm\\\"\"")
 }