-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
auth_test.go
57 lines (48 loc) · 1.62 KB
/
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
package middleware
import (
"encoding/base64"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestBasicAuth(t *testing.T) {
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
fn := func(u, p string) bool {
if u == "joe" && p == "secret" {
return true
}
return false
}
ba := BasicAuth(fn)
// Valid credentials
auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
req.Header.Set(echo.Authorization, auth)
assert.NoError(t, ba(c))
//---------------------
// Invalid credentials
//---------------------
// Incorrect password
auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
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.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.StatusUnauthorized, he.Code())
assert.Equal(t, Basic+" realm=Restricted", rec.Header().Get(echo.WWWAuthenticate))
// WebSocket
c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
assert.NoError(t, ba(c))
}