forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_auth_test.go
59 lines (51 loc) · 1.52 KB
/
key_auth_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestKeyAuth(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil)
res := httptest.NewRecorder()
c := e.NewContext(req, res)
config := KeyAuthConfig{
Validator: func(key string, c echo.Context) (bool, error) {
return key == "valid-key", nil
},
}
h := KeyAuthWithConfig(config)(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
// Valid key
auth := DefaultKeyAuthConfig.AuthScheme + " " + "valid-key"
req.Header.Set(echo.HeaderAuthorization, auth)
assert.NoError(t, h(c))
// Invalid key
auth = DefaultKeyAuthConfig.AuthScheme + " " + "invalid-key"
req.Header.Set(echo.HeaderAuthorization, auth)
he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code)
// Missing Authorization header
req.Header.Del(echo.HeaderAuthorization)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code)
// Key from custom header
config.KeyLookup = "header:API-Key"
h = KeyAuthWithConfig(config)(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
req.Header.Set("API-Key", "valid-key")
assert.NoError(t, h(c))
// Key from query string
config.KeyLookup = "query:key"
h = KeyAuthWithConfig(config)(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
q := req.URL.Query()
q.Add("key", "valid-key")
req.URL.RawQuery = q.Encode()
assert.NoError(t, h(c))
}