Files
upstream-chi/middleware/basic_auth_test.go
upstream-mirror 72c9f2ee75
Some checks failed
Test / test (1.24.x, ubuntu-latest) (push) Successful in 2m56s
Test / test (1.25.x, ubuntu-latest) (push) Successful in 2m15s
Test / test (1.26.x, ubuntu-latest) (push) Successful in 2m23s
Test / test (1.27.x, ubuntu-latest) (push) Failing after 3m56s
Test / test (1.24.x, windows-latest) (push) Has been cancelled
Test / test (1.25.x, windows-latest) (push) Has been cancelled
Test / test (1.26.x, windows-latest) (push) Has been cancelled
Test / test (1.27.x, windows-latest) (push) Has been cancelled
snapshot of https://github.com/go-chi/chi.git (master, 2026-09-15; blobs > 131072B omitted)
2026-09-15 21:48:17 +05:00

60 lines
1.2 KiB
Go

package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
)
var testAuthCreds = map[string]string{
"testUser": "testPassword",
}
func TestBasicAuth(t *testing.T) {
endpoint := "/secure"
r := chi.NewRouter()
r.Use(BasicAuth("localhost", testAuthCreds))
r.Get(endpoint, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("authentication accepted"))
}))
cases := []struct {
name string
digest string
expected int
}{
{
name: "no authorization header",
expected: http.StatusUnauthorized,
},
{
name: "invalid basic auth credentials",
digest: "Basic dGVzdFVzZXI6d3JvbmdwYXNzd29yZA==",
expected: http.StatusUnauthorized,
},
{
name: "valid basic auth credentials",
digest: "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk",
expected: http.StatusOK,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, endpoint, http.NoBody)
if c.digest != "" {
req.Header.Set("Authorization", c.digest)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if got := w.Code; got != c.expected {
t.Errorf("status code = %d, expected %d", got, c.expected)
}
})
}
}