Golang : Basic authentication with .htpasswd file
If you are looking to protect a web page with Basic Authentication. It can be done easily with Golang. In this tutorial, we will first explore how to implement basic authentication with username and password in the source code. Follow by sourcing the username/password from the .htpasswd
file.
This code example will prompt a user for username and password before allowing access.
package main
import (
"encoding/base64"
"github.com/gorilla/mux"
"net/http"
"strings"
)
var username = []byte("hello")
var password = []byte("password")
func BasicAuth(w http.ResponseWriter, r *http.Request, user, pass []byte) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
return pair[0] == string(user) && pair[1] == string(pass)
}
func Home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func Protected(w http.ResponseWriter, r *http.Request) {
// pass from global variables
if BasicAuth(w, r, username, password) {
w.Write([]byte("Welcome to the Protected Page!!"))
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", Home)
mx.HandleFunc("/protectedpage/", Protected)
http.ListenAndServe(":8080", mx)
}
run this code and point your browser to http://localhost:8080/protectedpage/
. You will be prompted for the username and password, which is hello
and password
.
If you are looking for more secure option, you can choose to load the username and password from .htpasswd
file.
Use http://www.htaccesstools.com/htpasswd-generator/ to generate a .htpasswd
file. In this example, we will use username
and password
Make sure the file has only 1 line.
cat .htpasswd
username:$apr1$F9tXeu9r$oairgF8rFh2oRUC4Dl9v/1
We will read the .htpasswd
file with the github.com/abbot/go-http-auth
package.
Run this code and point your browser to http://localhost:8080/protectedpage/
. You will be prompted for the username and password, which is username
and password
.
package main
import (
"fmt"
auth "github.com/abbot/go-http-auth"
"github.com/gorilla/mux"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func Protected(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
w.Write([]byte(fmt.Sprintf("Hello, %s!", r.Username)))
}
func main() {
// read from .htpasswd file
htpasswd := auth.HtpasswdFileProvider("./.htpasswd")
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
mx := mux.NewRouter()
mx.HandleFunc("/", Home)
mx.HandleFunc("/protectedpage/", authenticator.Wrap(Protected))
http.ListenAndServe(":8080", mx)
}
The outcome should be the same as the previous code, except that this time, the username and password taken from a file instead of hard coded into the source code.
References :
See also : Golang : How to implement two-factor authentication?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.9k Golang : How to get quoted string into another string?
+22.6k Golang : Calculate time different
+22.5k Golang : simulate tail -f or read last line from log file example
+7.8k Findstr command the Grep equivalent for Windows
+17.6k Golang : Simple client server example
+11.3k Golang : Change date format to yyyy-mm-dd
+9.7k Golang : Check if user agent is a robot or crawler example
+31.7k Golang : Validate email address with regular expression
+8.8k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+14.9k Golang : Get HTTP protocol version example
+4.4k MariaDB/MySQL : How to get version information
+9k Golang : Temperatures conversion example