|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "github.com/labstack/echo" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "testing" |
| 9 | +) |
| 10 | + |
| 11 | +func TestBasicAuth(t *testing.T) { |
| 12 | + req, _ := http.NewRequest(echo.POST, "/", nil) |
| 13 | + res := &echo.Response{Writer: httptest.NewRecorder()} |
| 14 | + c := echo.NewContext(req, res, echo.New()) |
| 15 | + fn := func(u, p string) bool { |
| 16 | + if u == "joe" && p == "secret" { |
| 17 | + return true |
| 18 | + } |
| 19 | + return false |
| 20 | + } |
| 21 | + b := BasicAuth(fn) |
| 22 | + |
| 23 | + //------------------- |
| 24 | + // Valid credentials |
| 25 | + //------------------- |
| 26 | + |
| 27 | + auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret")) |
| 28 | + req.Header.Set(echo.Authorization, auth) |
| 29 | + if b(c) != nil { |
| 30 | + t.Error("basic auth should pass") |
| 31 | + } |
| 32 | + |
| 33 | + // Case insensitive |
| 34 | + auth = "basic " + base64.StdEncoding.EncodeToString([]byte("joe:secret")) |
| 35 | + req.Header.Set(echo.Authorization, auth) |
| 36 | + if b(c) != nil { |
| 37 | + t.Error("basic auth should ignore case and pass") |
| 38 | + } |
| 39 | + |
| 40 | + //--------------------- |
| 41 | + // Invalid credentials |
| 42 | + //--------------------- |
| 43 | + |
| 44 | + auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte(" joe: secret")) |
| 45 | + req.Header.Set(echo.Authorization, auth) |
| 46 | + b = BasicAuth(fn) |
| 47 | + if b(c) == nil { |
| 48 | + t.Error("basic auth should fail") |
| 49 | + } |
| 50 | + |
| 51 | + // Invalid scheme |
| 52 | + auth = "foo " + base64.StdEncoding.EncodeToString([]byte(" joe: secret")) |
| 53 | + req.Header.Set(echo.Authorization, auth) |
| 54 | + b = BasicAuth(fn) |
| 55 | + if b(c) == nil { |
| 56 | + t.Error("basic auth should fail for invalid scheme") |
| 57 | + } |
| 58 | +} |
0 commit comments