HTTP Basic Access Authorization In Golang

One of the simplest and oldest methods of authorization is HTTP Basic authorization. While it isn’t as secure as the Users service of App Engine or the OAuth authorization model, it’s easy to implement and looks visually impressive depending on the user’s browser.

Here’s a picture of the HTTP Basic authorization prompt in IE10 on Windows 8:

The variable authorization contains a base64 encoded hash generated by the user’s browser, created by concatenating the username and password together with a colon: username:passwordR represents a http.Request reference, c is appengine.Context, and w is http.ResponseWriter.

//Get the authorization header.
authorization_array := r.Header["Authorization"]
if len(authorization_array) > 0 {
    authorization := strings.TrimSpace(authorization_array[0])
    c.Infof("Authorization: ", authorization)
} else {
    w.Header().Set("WWW-Authenticate", "Basic realm=\"user\"")
    http.Error(w, http.StatusText(401), 401)