-
-
Save myrkvi/5c3386198aa9fbd14be7 to your computer and use it in GitHub Desktop.
Golang Basic Auth
This file contains 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 utils | |
import ( | |
"encoding/base64" | |
"net/http" | |
"strings" | |
) | |
func BasicAuth(handler http.HandlerFunc, username, password string) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
authError := func() { | |
w.Header().Set("WWW-Authenticate", "Basic realm=\"Zork\"") | |
http.Error(w, "authorization failed", http.StatusUnauthorized) | |
} | |
auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2) | |
if len(auth) != 2 || auth[0] != "Basic" { | |
authError() | |
return | |
} | |
payload, err := base64.StdEncoding.DecodeString(auth[1]) | |
if err != nil { | |
authError() | |
return | |
} | |
pair := strings.SplitN(string(payload), ":", 2) | |
if len(pair) != 2 || !(pair[0] == username && pair[1] == password) { | |
authError() | |
return | |
} | |
handler(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment