Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Skipper Unit Test In BasicBasicAuthConfig and Add More Detail Explanation regarding BasicAuthValidator #2461

Merged
merged 2 commits into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions middleware/basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ type (
}

// BasicAuthValidator defines a function to validate BasicAuth credentials.
// The function should return a boolean indicating whether the credentials are valid,
// and an error if any error occurs during the validation process.
BasicAuthValidator func(string, string, echo.Context) (bool, error)
)

Expand Down
19 changes: 18 additions & 1 deletion middleware/basic_auth_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"bytes"
"encoding/base64"
"net/http"
"net/http/httptest"
Expand All @@ -25,20 +26,36 @@ func TestBasicAuth(t *testing.T) {
h := BasicAuth(f)(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
s := func(c echo.Context) bool {
RyoKusnadi marked this conversation as resolved.
Show resolved Hide resolved
auth := c.Request().Header.Get(echo.HeaderAuthorization)
if strings.HasPrefix(auth, basic) {
decoded, err := base64.StdEncoding.DecodeString(auth[len(basic)+1:])
if err != nil {
return false
}
return bytes.Equal(decoded, []byte("joe:skip"))
}
return false
}

// Valid credentials
auth := basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
req.Header.Set(echo.HeaderAuthorization, auth)
assert.NoError(t, h(c))

h = BasicAuthWithConfig(BasicAuthConfig{
Skipper: nil,
Skipper: s,
Validator: f,
Realm: "someRealm",
})(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})

// Skipped Request
auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:skip"))
req.Header.Set(echo.HeaderAuthorization, auth)
assert.NoError(t, h(c))

// Valid credentials
auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
req.Header.Set(echo.HeaderAuthorization, auth)
Expand Down