Skip to content

Commit

Permalink
add BasicAuthWithBcryptHashAndPrompt middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Dec 9, 2024
1 parent 3c3ee31 commit 7ecfa2e
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 0 deletions.
27 changes: 27 additions & 0 deletions basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,33 @@ func BasicAuthWithPrompt(user, passwd string) func(http.Handler) http.Handler {
}
}

// BasicAuthWithBcryptHashAndPrompt middleware requires basic auth and matches user & bcrypt hashed password
// If the user is not authorized, it will prompt for basic auth
func BasicAuthWithBcryptHashAndPrompt(user, hashedPassword string) func(http.Handler) http.Handler {
checkFn := func(reqUser, reqPasswd string) bool {
if reqUser != user {
return false
}
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(reqPasswd))
return err == nil
}

return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// extract basic auth from request
u, p, ok := r.BasicAuth()
if ok && checkFn(u, p) {
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), contextKey(baContextKey), true)))
return
}
// not authorized, prompt for basic auth
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
return http.HandlerFunc(fn)
}
}

// GenerateBcryptHash generates a bcrypt hash from a password
func GenerateBcryptHash(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
Expand Down
84 changes: 84 additions & 0 deletions basic_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,87 @@ func TestArgon2InvalidInputs(t *testing.T) {
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
})
}

func TestBasicAuthWithBcryptHashAndPrompt(t *testing.T) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte("good"), bcrypt.MinCost)
require.NoError(t, err)
t.Logf("hashed password: %s", string(hashedPassword))

mw := BasicAuthWithBcryptHashAndPrompt("dev", string(hashedPassword))

ts := httptest.NewServer(mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("request %s", r.URL)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("blah"))
require.NoError(t, err)
assert.True(t, IsAuthorized(r.Context()))
})))
defer ts.Close()

u := fmt.Sprintf("%s%s", ts.URL, "/something")
client := http.Client{Timeout: 5 * time.Second}

tests := []struct {
name string
username string
password string
expectedStatus int
checkPrompt bool
}{
{
name: "no auth provided",
username: "",
password: "",
expectedStatus: http.StatusUnauthorized,
checkPrompt: true,
},
{
name: "correct credentials",
username: "dev",
password: "good",
expectedStatus: http.StatusOK,
checkPrompt: false,
},
{
name: "wrong username",
username: "wrong",
password: "good",
expectedStatus: http.StatusUnauthorized,
checkPrompt: true,
},
{
name: "wrong password",
username: "dev",
password: "bad",
expectedStatus: http.StatusUnauthorized,
checkPrompt: true,
},
{
name: "empty password",
username: "dev",
password: "",
expectedStatus: http.StatusUnauthorized,
checkPrompt: true,
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req, err := http.NewRequest("GET", u, http.NoBody)
require.NoError(t, err)

if tc.username != "" || tc.password != "" {
req.SetBasicAuth(tc.username, tc.password)
}

resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, tc.expectedStatus, resp.StatusCode)

if tc.checkPrompt {
assert.Equal(t, `Basic realm="restricted", charset="UTF-8"`, resp.Header.Get("WWW-Authenticate"),
"should include WWW-Authenticate header")
}
})
}
}

0 comments on commit 7ecfa2e

Please sign in to comment.