golib/auth/request_example_test.go
copilot-swe-agent[bot] 9b79800b07 refactor: remove Challenge() method; use w.Header().Set("WWW-Authenticate", ...) directly
Co-authored-by: coolaj86 <122831+coolaj86@users.noreply.github.com>
2026-03-02 08:10:17 +00:00

38 lines
1.1 KiB
Go

package auth_test
import (
"fmt"
"net/http"
"github.com/therootcompany/golib/auth"
)
// exampleCreds is a toy BasicAuthenticator used only in the example below.
type exampleCreds struct{}
func (exampleCreds) Authenticate(username, password string) (auth.BasicPrinciple, error) {
return nil, fmt.Errorf("not implemented")
}
// ExampleRequestAuthenticator shows the typical usage pattern.
// Build a RequestAuthenticator once (at startup), attach your credential
// store as the Authenticator, then call Authenticate in each handler.
// Set the WWW-Authenticate header before writing a 401 so the browser
// knows which scheme to offer.
func ExampleRequestAuthenticator() {
ra := auth.NewRequestAuthenticator()
ra.Authenticator = exampleCreds{} // swap in your real credential store
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
principle, err := ra.Authenticate(r)
if err != nil {
if ra.WWWAuthenticate != "" {
w.Header().Set("WWW-Authenticate", ra.WWWAuthenticate)
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "hello %s", principle.ID())
})
}