2016-04-28 06:08:06 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"net/http"
|
2016-09-23 07:53:44 +02:00
|
|
|
"net/http/httptest"
|
2016-04-28 06:08:06 +02:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBasicAuth(t *testing.T) {
|
|
|
|
e := echo.New()
|
2016-09-23 07:53:44 +02:00
|
|
|
req, _ := http.NewRequest(echo.GET, "/", nil)
|
|
|
|
res := httptest.NewRecorder()
|
2016-04-28 06:08:06 +02:00
|
|
|
c := e.NewContext(req, res)
|
2017-01-05 22:12:31 +02:00
|
|
|
f := func(u, p string, c echo.Context) bool {
|
2016-04-28 06:08:06 +02:00
|
|
|
if u == "joe" && p == "secret" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
h := BasicAuth(f)(func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "test")
|
|
|
|
})
|
|
|
|
|
|
|
|
// Valid credentials
|
|
|
|
auth := basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
|
2016-09-23 07:53:44 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, auth)
|
2016-04-28 06:08:06 +02:00
|
|
|
assert.NoError(t, h(c))
|
|
|
|
|
2017-01-03 06:12:06 +02:00
|
|
|
// Invalid credentials
|
|
|
|
auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:invalid-password"))
|
2016-09-23 07:53:44 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, auth)
|
2016-04-28 06:08:06 +02:00
|
|
|
he := h(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, http.StatusUnauthorized, he.Code)
|
|
|
|
assert.Equal(t, basic+" realm=Restricted", res.Header().Get(echo.HeaderWWWAuthenticate))
|
|
|
|
|
2017-01-03 06:12:06 +02:00
|
|
|
// Missing Authorization header
|
|
|
|
req.Header.Del(echo.HeaderAuthorization)
|
2016-04-28 06:08:06 +02:00
|
|
|
he = h(c).(*echo.HTTPError)
|
2017-01-05 22:12:31 +02:00
|
|
|
assert.Equal(t, http.StatusUnauthorized, he.Code)
|
2016-04-28 06:08:06 +02:00
|
|
|
|
|
|
|
// Invalid Authorization header
|
|
|
|
auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
|
2016-09-23 07:53:44 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, auth)
|
2016-04-28 06:08:06 +02:00
|
|
|
he = h(c).(*echo.HTTPError)
|
2017-01-05 22:12:31 +02:00
|
|
|
assert.Equal(t, http.StatusUnauthorized, he.Code)
|
2016-04-28 06:08:06 +02:00
|
|
|
}
|