Golang net/http.Request.BasicAuth() function example

package net/http

Golang net/http.Request.BasicAuth() function usage example

 package main

 import (
 "fmt"
 "net/http"
 "strings"
 "encoding/base64"
 )

 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) {

 // 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"))

 // ---- HERE ! -----

 username, password, ok := r.BasicAuth()

 fmt.Println("username : ", username)
 fmt.Println("password : ", password)
 fmt.Println("ok : ", ok)
 }

 func main() {
 http.HandleFunc("/", home)
 http.ListenAndServe(":8080", nil)
 }

Sample output :

username :

password :

ok : false

after entering username and password

username : username

password : password

ok : true

References :

http://golang.org/pkg/net/http/#Request.BasicAuth

https://www.socketloop.com/tutorials/golang-basic-authentication-with-htpasswd-file

Advertisement