-
-
Save ttys3/afef3b296683ec983cd55ef0e165ef8e to your computer and use it in GitHub Desktop.
HTTP Basic Auth example in Go (based on http://stackoverflow.com/a/21937924/556573 + bespoke middleware implementation)
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 ( | |
"encoding/base64" | |
"github.com/gorilla/mux" | |
"net/http" | |
"strings" | |
) | |
func main() { | |
r := mux.NewRouter() | |
r.HandleFunc("/form", use(myHandler, basicAuth)) | |
http.Handle("/", r) | |
http.ListenAndServe(":9900", nil) | |
} | |
// use provides a cleaner interface for chaining middleware for single routes. | |
// Middleware functions are simple HTTP handlers (w http.ResponseWriter, r *http.Request) | |
// | |
// r.HandleFunc("/login", use(loginHandler, rateLimit, csrf)) | |
// r.HandleFunc("/form", use(formHandler, csrf)) | |
// r.HandleFunc("/about", aboutHandler) | |
// | |
// See https://gist.github.com/elithrar/7600878#comment-955958 for how to extend it to suit simple http.Handler's | |
func use(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc { | |
for _, m := range middleware { | |
h = m(h) | |
} | |
return h | |
} | |
func myHandler(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Authenticated!")) | |
return | |
} | |
// Leverages nemo's answer in http://stackoverflow.com/a/21937924/556573 | |
func basicAuth(h http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) | |
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) | |
if len(s) != 2 { | |
http.Error(w, "Not authorized", 401) | |
return | |
} | |
b, err := base64.StdEncoding.DecodeString(s[1]) | |
if err != nil { | |
http.Error(w, err.Error(), 401) | |
return | |
} | |
pair := strings.SplitN(string(b), ":", 2) | |
if len(pair) != 2 { | |
http.Error(w, "Not authorized", 401) | |
return | |
} | |
if pair[0] != "username" || pair[1] != "password" { | |
http.Error(w, "Not authorized", 401) | |
return | |
} | |
h.ServeHTTP(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment