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

View File

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