sdk-go icon indicating copy to clipboard operation
sdk-go copied to clipboard

[Webhook] Implement Auth in webhook

Open n3wscott opened this issue 6 years ago • 3 comments

n3wscott avatar Mar 07 '19 01:03 n3wscott

Is this solved by https://github.com/cloudevents/sdk-go/pull/491 ?

slinkydeveloper avatar May 20 '20 08:05 slinkydeveloper

No, did not touch the auth part of the webhook

n3wscott avatar Jun 02 '20 14:06 n3wscott

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:

  1. is this the correct way to use WithMiddleware()
  2. if so, I can open a PR for MiddlewareBasicAuth if heading in the right direction
  3. which other auth schemes do we want to support?

embano1 avatar Jun 25 '21 20:06 embano1