I am developing a simple blog engine in go using only the standard libraries (and the mysql driver )
For the admin I am using Basic HTTP Auth
func IsAllowed(w http.ResponseWriter, r *http.Request) bool {
u, p, ok := r.BasicAuth()
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
return false
}
if u != "devnull" || p != "veryfancypw" {
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
return false
}
return true
}
This is obviously not ideal as the user pw should not be hardcoded this way.
What is the best way to store these credentials e.g. in a config file but without external packages ? Is it desirable to pass it as a parameter when I launch go run main.go or ?
UPDATE
I accepted @stdtom reply as it is very comprehensive. I opted for storing in the environmental variables so we have:
func IsAllowed(w http.ResponseWriter, r *http.Request) bool {
u, p, ok := r.BasicAuth()
boss := os.Getenv("BOSS")
bosspw := os.Getenv("BOSSPW")
// printf("Debug: %s, debugging: %s\n", boss, bosspw)
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
return false
}
if u != boss || p != bosspw {
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
return false
}
return true
}
For this to work you need to add these variables in .zshrc (on a mac) or if you use bash .bashrc
export BOSS=myusername
export BOSSPW="my long and difficult to get password"
As the accepted reply suggests "Privileged users can access the environment variables..." but my scenario is based on your running your own machine so if someone gets access to it the user/pw to the admin interface of your blog is probably the least of your problems.
I think this was very useful as most example you find online about using Basic HTTP Auth in GO just show hardcoded username and passwords which is of course a very bad idea.