BasicAuth returns a middleware that authenticates users with Basic Auth.
(realm string, authenticator Authenticator)
| 55 | |
| 56 | // BasicAuth returns a middleware that authenticates users with Basic Auth. |
| 57 | func BasicAuth(realm string, authenticator Authenticator) MiddlewareFunc { |
| 58 | if authenticator == nil { |
| 59 | authenticator = noopAuthenticator |
| 60 | } |
| 61 | writeUnauthorized := func(w http.ResponseWriter) { |
| 62 | w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm)) |
| 63 | w.WriteHeader(http.StatusUnauthorized) |
| 64 | } |
| 65 | return func(next http.Handler) http.Handler { |
| 66 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 67 | username, password, ok := r.BasicAuth() |
| 68 | if !ok { |
| 69 | writeUnauthorized(w) |
| 70 | return |
| 71 | } |
| 72 | authenticated, err := authenticator.Authenticate(username, password) |
| 73 | if err != nil { |
| 74 | webhandlers.Error(w, r, err) |
| 75 | return |
| 76 | } |
| 77 | if !authenticated { |
| 78 | writeUnauthorized(w) |
| 79 | return |
| 80 | } |
| 81 | next.ServeHTTP(w, r) |
| 82 | }) |
| 83 | } |
| 84 | } |