...

Source file src/github.com/go-chi/chi/middleware/basic_auth.go

Documentation: github.com/go-chi/chi/middleware

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  )
     7  
     8  // BasicAuth implements a simple middleware handler for adding basic http auth to a route.
     9  func BasicAuth(realm string, creds map[string]string) func(next http.Handler) http.Handler {
    10  	return func(next http.Handler) http.Handler {
    11  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    12  			user, pass, ok := r.BasicAuth()
    13  			if !ok {
    14  				basicAuthFailed(w, realm)
    15  				return
    16  			}
    17  
    18  			credPass, credUserOk := creds[user]
    19  			if !credUserOk || pass != credPass {
    20  				basicAuthFailed(w, realm)
    21  				return
    22  			}
    23  
    24  			next.ServeHTTP(w, r)
    25  		})
    26  	}
    27  }
    28  
    29  func basicAuthFailed(w http.ResponseWriter, realm string) {
    30  	w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
    31  	w.WriteHeader(http.StatusUnauthorized)
    32  }
    33  

View as plain text