sdk-go
sdk-go copied to clipboard
[Webhook] Implement Auth in webhook
Is this solved by https://github.com/cloudevents/sdk-go/pull/491 ?
No, did not touch the auth part of the webhook
Just had to implement this myself, so definitely something useful. In my case I needed basic_auth, e.g.:
// other http protocol stuff
... ce.WithMiddleware(func(next http.Handler) http.Handler {
return withBasicAuth(ctx, next, cfg.Auth.BasicAuth.Username, cfg.Auth.BasicAuth.Password)
})
// withBasicAuth enforces basic auth as a middleware for the given username and
// password
func withBasicAuth(_ context.Context, next http.Handler, u, p string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
// reduce brute-force guessing attacks with constant-time comparisons
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
expectedUsernameHash := sha256.Sum256([]byte(u))
expectedPasswordHash := sha256.Sum256([]byte(p))
usernameMatch := subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1
passwordMatch := subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}
Questions:
- is this the correct way to use
WithMiddleware() - if so, I can open a PR for
MiddlewareBasicAuthif heading in the right direction - which other auth schemes do we want to support?