diff --git a/auth.go b/auth.go index dc37a85..bb6ff69 100644 --- a/auth.go +++ b/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) diff --git a/auth_test.go b/auth_test.go index bb0ed73..2e9de08 100644 --- a/auth_test.go +++ b/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\\\"\"") }