GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — interpose/middleware/basicAuth.go at master · carbocation/interpose Expand file tree/ Copy pathbasicAuth.goMore file actions 69 lines (61 loc) · 2.16 KB / Copy pathbasicAuth.goFile metadata and controls69 lines (61 loc) · 2.16 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 package middleware import ( "crypto/sha256" "crypto/subtle" "encoding/base64" "net/http" "strings" ) // User is the authenticated username that was extracted from the request. type User string // BasicRealm is used when setting the WWW-Authenticate response header. var BasicRealm = "Authorization Required" // Basic returns a Handler that authenticates via Basic Auth. Writes a http.StatusUnauthorized // if authentication fails func BasicAuth(username string, password string) func(http.Handler) http.Handler { var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) return func(next http.Handler) http.Handler { return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { auth := req.Header.Get("Authorization") if !SecureCompare(auth, "Basic "+siteAuth) { unauthorized(res) return } next.ServeHTTP(res, req) }) } } // BasicAuthFunc returns a Handler that authenticates via Basic Auth using the provided function. // The function should return true for a valid username/password combination. func BasicAuthFunc(authfn func(string, string, *http.Request) bool) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { auth := req.Header.Get("Authorization") if len(auth) < 6 || auth[:6] != "Basic " { unauthorized(res) return } b, err := base64.StdEncoding.DecodeString(auth[6:]) if err != nil { unauthorized(res) return } tokens := strings.SplitN(string(b), ":", 2) if len(tokens) != 2 || !authfn(tokens[0], tokens[1], req) { unauthorized(res) return } next.ServeHTTP(res, req) }) } } // SecureCompare performs a constant time compare of two strings to limit timing attacks. func SecureCompare(given string, actual string) bool { givenSha := sha256.Sum256([]byte(given)) actualSha := sha256.Sum256([]byte(actual)) return subtle.ConstantTimeCompare(givenSha[:], actualSha[:]) == 1 } func unauthorized(res http.ResponseWriter) { res.Header().Set("WWW-Authenticate", "Basic realm=\""+BasicRealm+"\"") http.Error(res, "Not Authorized", http.StatusUnauthorized) } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |