Skip to content

Instantly share code, notes, and snippets.

@vardius
Last active June 11, 2020 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vardius/a8da23717acb20c16cdf113647de0e2b to your computer and use it in GitHub Desktop.
Save vardius/a8da23717acb20c16cdf113647de0e2b to your computer and use it in GitHub Desktop.
Basic HTTP authentication with Go
package main
import (
"crypto/subtle"
"fmt"
"log"
"net/http"
)
var (
requiredUser = []byte("gordon")
requiredPassword = []byte("secret!")
)
func BasicAuth(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if !hasAuth || subtle.ConstantTimeCompare(requiredUser, []byte(user)) != 1 || subtle.ConstantTimeCompare(requiredPassword, []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func index(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Not protected!\n")
}
func protected(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Protected!\n")
}
func main() {
http.HandleFunc("/", index)
http.Handle("/protected", BasicAuth(http.HandlerFunc(protected)))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment