gobot.io/x/gobot@v1.16.0/api/basic_auth.go (about) 1 package api 2 3 import ( 4 "crypto/subtle" 5 "encoding/base64" 6 "net/http" 7 ) 8 9 // BasicAuth returns basic auth handler. 10 func BasicAuth(username, password string) http.HandlerFunc { 11 // Inspired by https://github.com/codegangsta/martini-contrib/blob/master/auth/ 12 return func(res http.ResponseWriter, req *http.Request) { 13 if !secureCompare(req.Header.Get("Authorization"), 14 "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)), 15 ) { 16 res.Header().Set("WWW-Authenticate", 17 "Basic realm=\"Authorization Required\"", 18 ) 19 http.Error(res, "Not Authorized", http.StatusUnauthorized) 20 } 21 } 22 } 23 24 func secureCompare(given string, actual string) bool { 25 if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 { 26 return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1 27 } 28 // Securely compare actual to itself to keep constant time, 29 // but always return false 30 return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false 31 }