I’m trying to build an api that will eventually receive json data from the client and save to a file, however I’m stuck trying to get basic auth working. The middleware is giving me a problem. I keep re-reading the info I can find on it but I’m missing something. Can someone get a look at this code and explain what I’m doing wrong?
‘’’
package main
import (
“log”
“net/http”
“fmt”
)
func apitest(w http.ResponseWriter, r *http.Request) http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
})
}
func basicAuth(h http.Handler) http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, _ := r.BasicAuth()
var myUser string = “kevin”
var myPass string = “kevin”
if myUser != user || myPass != pass {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
I got errors because apitest didn’t implement httpServe method. I rewrote it slightly to just use handleFuncs instead. And I changed it to http (just because I was lazy and didn’t want to generate certificate and key. But now it works:
Thank you for correcting it. I want to make sure I’m understanding this properly. Changing the basicauth var to a handler , is that because it’s being called as part of HandleFunc in the main? Then the apitest function is because that’s what is getting passed in the anon function, right?
Hi. I’m not sure if I know what you mean. You can use http.Handler or http.HandleFunc but http.Handler is an interface which must implement ServeHTTP(w, r) interface. So usually it is simpler to just use HandlerFunc. I guess Handler is more handy (pun intended) then you want an object with state for example. I don’t think I answered your question
Hi, I have recently worked with a project that used HTTP basic auth to gate access to the app’s pages.
I found it works for my purposes, but with two^H^H^Hthree caveats:
Keep in mind HTTP basic auth is not secure! Place your service behind an HTTP reverse proxy so TLS will protect the auth info (which is sent in HTTP headers).
Logging out of HTTP basic auth sessions is difficult in modern browsers. They cache HTTP headers aggressively, requiring Javascript hacks to clear the state. Don’t ask me more about it, I barely understand it myself But there’s discussion below:
This doesn’t support multiple ‘users’ (different roles etc.). Use a more advanced account mechanism if you need that.