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
+26.2k Mac/Linux and Golang : Fix bind: address already in use error
+17.1k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+13.1k Golang : Get terminal width and height example
+26.8k Golang : How to check if a connection to database is still alive ?
+16k Golang : Get digits from integer before and after given position example
+14.4k Golang : Get uploaded file name or access uploaded files
+6k Cash Flow : 50 days to pay your credit card debt
+32.3k Golang : Convert []string to []byte examples
+6.2k PageSpeed : Clear or flush cache on web server
+11.1k Golang : Create S3 bucket with official aws-sdk-go package
+28.2k Golang : Move file to another directory
+28.7k Golang : Change a file last modified date and time