httpauth currently provides HTTP Basic Authentication middleware for for Go.
Note that httpauth is completely compatible with Goji, a minimal web framework for Go, but as it satisfies http.Handler it can be used beyond Goji itself.
httpauth provides a SimpleBasicAuth
function to get you up and running. Particularly ideal for development servers.
Note that HTTP Basic Authentication credentials are sent over the wire "in the clear" (read: plaintext!) and therefore should not be considered a robust way to secure a HTTP server. If you're after that, you'll need to use SSL/TLS ("HTTPS") at a minimum.
This version is forked by Gerhard Häring gh@ghaering.de to use a callback thet checks username/password instead of a single valid username/password combination.
package main
import(
"net/http"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
)
func main() {
goji.Use(httpauth.SimpleBasicAuth(func(user string, password string) bool {
return user == "dave" && password == "secret"
}))
goji.Use(SomeOtherMiddleware)
// myHandler requires HTTP Basic Auth
goji.Get("/thing", myHandler)
goji.Serve()
}
If you're looking for a little more control over the process, you can instead pass a httpauth.AuthOptions
struct to httpauth.BasicAuth
instead. This allows you to:
- Configure the authentication realm
- Provide your own UnauthorizedHandler (anything that satisfies
http.Handler
) so you can return a better looking 401 page.
func main() {
authOpts := httpauth.AuthOptions{
Realm: "DevCo",
AuthFunc: func(user string, password string) bool {
return user == correctUser && password == correctPassword
},
UnauthorizedHandler: myUnauthorizedHandler,
}
goji.Use(BasicAuth(authOpts))
goji.Use(SomeOtherMiddleware)
goji.Get("/thing", myHandler)
goji.Serve()
}
Since it's all http.Handler
, httpauth works with gorilla/mux (and most other routers) as well:
package main
import (
"net/http"
"github.com/goji/httpauth"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", myHandler)
http.Handle("/", httpauth.SimpleBasicAuth(func(user string, password string) bool {
return user == correctUser && password == correctPassword
})(r))
http.ListenAndServe(":7000", nil)
}
func myHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
If you're using vanilla net/http:
package main
import(
"net/http"
"github.com/goji/httpauth"
)
func main() {
http.Handle("/", httpauth.SimpleBasicAuth(func(user string, password string) bool {
return user == correctUser && password == correctPassword
})(http.HandlerFunc(hello)))
http.ListenAndServe(":7000", nil)
}
Send a pull request! Note that features on the (informal) roadmap include HTTP Digest Auth and the potential for supplying your own user/password comparison function.