Last active
June 11, 2020 05:12
-
-
Save vardius/a8da23717acb20c16cdf113647de0e2b to your computer and use it in GitHub Desktop.
Basic HTTP authentication with Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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