mirror of
https://github.com/labstack/echo.git
synced 2024-12-24 20:14:31 +02:00
commit
e0a40f864c
1
echo.go
1
echo.go
@ -134,6 +134,7 @@ const (
|
||||
Location = "Location"
|
||||
Upgrade = "Upgrade"
|
||||
Vary = "Vary"
|
||||
WWWAuthenticate = "WWW-Authenticate"
|
||||
|
||||
//-----------
|
||||
// Protocols
|
||||
|
@ -18,7 +18,6 @@ const (
|
||||
// BasicAuth returns an HTTP basic authentication middleware.
|
||||
//
|
||||
// For valid credentials it calls the next handler.
|
||||
// For invalid Authorization header it sends "404 - Bad Request" response.
|
||||
// For invalid credentials, it sends "401 - Unauthorized" response.
|
||||
func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
|
||||
return func(c *echo.Context) error {
|
||||
@ -29,7 +28,6 @@ func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
|
||||
|
||||
auth := c.Request().Header.Get(echo.Authorization)
|
||||
l := len(Basic)
|
||||
he := echo.NewHTTPError(http.StatusBadRequest)
|
||||
|
||||
if len(auth) > l+1 && auth[:l] == Basic {
|
||||
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
|
||||
@ -41,11 +39,11 @@ func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
|
||||
if fn(cred[:i], cred[i+1:]) {
|
||||
return nil
|
||||
}
|
||||
he.SetCode(http.StatusUnauthorized)
|
||||
c.Response().Header().Set(echo.WWWAuthenticate, Basic + " realm=Restricted")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return he
|
||||
return echo.NewHTTPError(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
@ -36,17 +36,20 @@ func TestBasicAuth(t *testing.T) {
|
||||
req.Header.Set(echo.Authorization, auth)
|
||||
he := ba(c).(*echo.HTTPError)
|
||||
assert.Equal(t, http.StatusUnauthorized, he.Code())
|
||||
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
|
||||
|
||||
// Empty Authorization header
|
||||
req.Header.Set(echo.Authorization, "")
|
||||
he = ba(c).(*echo.HTTPError)
|
||||
assert.Equal(t, http.StatusBadRequest, he.Code())
|
||||
assert.Equal(t, http.StatusUnauthorized, he.Code())
|
||||
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
|
||||
|
||||
// Invalid Authorization header
|
||||
auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
|
||||
req.Header.Set(echo.Authorization, auth)
|
||||
he = ba(c).(*echo.HTTPError)
|
||||
assert.Equal(t, http.StatusBadRequest, he.Code())
|
||||
assert.Equal(t, http.StatusUnauthorized, he.Code())
|
||||
assert.Equal(t, Basic + " realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
|
||||
|
||||
// WebSocket
|
||||
c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
|
||||
|
Loading…
Reference in New Issue
Block a user