Skip to content

Commit e0a40f8

Browse files
committed
Merge pull request #192 from labstack/issue-180
Closes #180
2 parents e7b1358 + 8aaf620 commit e0a40f8

File tree

3 files changed

+8
-6
lines changed

3 files changed

+8
-6
lines changed

echo.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ const (
134134
Location = "Location"
135135
Upgrade = "Upgrade"
136136
Vary = "Vary"
137+
WWWAuthenticate = "WWW-Authenticate"
137138

138139
//-----------
139140
// Protocols

middleware/auth.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ const (
1818
// BasicAuth returns an HTTP basic authentication middleware.
1919
//
2020
// For valid credentials it calls the next handler.
21-
// For invalid Authorization header it sends "404 - Bad Request" response.
2221
// For invalid credentials, it sends "401 - Unauthorized" response.
2322
func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
2423
return func(c *echo.Context) error {
@@ -29,7 +28,6 @@ func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
2928

3029
auth := c.Request().Header.Get(echo.Authorization)
3130
l := len(Basic)
32-
he := echo.NewHTTPError(http.StatusBadRequest)
3331

3432
if len(auth) > l+1 && auth[:l] == Basic {
3533
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
@@ -41,11 +39,11 @@ func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
4139
if fn(cred[:i], cred[i+1:]) {
4240
return nil
4341
}
44-
he.SetCode(http.StatusUnauthorized)
42+
c.Response().Header().Set(echo.WWWAuthenticate, Basic + " realm=Restricted")
4543
}
4644
}
4745
}
4846
}
49-
return he
47+
return echo.NewHTTPError(http.StatusUnauthorized)
5048
}
5149
}

middleware/auth_test.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,17 +36,20 @@ func TestBasicAuth(t *testing.T) {
3636
req.Header.Set(echo.Authorization, auth)
3737
he := ba(c).(*echo.HTTPError)
3838
assert.Equal(t, http.StatusUnauthorized, he.Code())
39+
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
3940

4041
// Empty Authorization header
4142
req.Header.Set(echo.Authorization, "")
4243
he = ba(c).(*echo.HTTPError)
43-
assert.Equal(t, http.StatusBadRequest, he.Code())
44+
assert.Equal(t, http.StatusUnauthorized, he.Code())
45+
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
4446

4547
// Invalid Authorization header
4648
auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
4749
req.Header.Set(echo.Authorization, auth)
4850
he = ba(c).(*echo.HTTPError)
49-
assert.Equal(t, http.StatusBadRequest, he.Code())
51+
assert.Equal(t, http.StatusUnauthorized, he.Code())
52+
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
5053

5154
// WebSocket
5255
c.Request().Header.Set(echo.Upgrade, echo.WebSocket)

0 commit comments

Comments
 (0)