Fixes important bug in Basic Auth when using custom realm.

This commit is contained in:
Manu Mtz-Almeida 2015-05-19 20:15:28 +02:00
parent 0cb52ccef7
commit 81b08a554e
2 changed files with 6 additions and 7 deletions

View File

@ -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)

View File

@ -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\\\"\"")
}