authentication system for a web app in go

Here is a simple example of an authentication system utilizing middleware in Go:

  1. First, let's create a struct for our user model to store user data:
main.go
type User struct {
    Username string
    PasswordHash []byte
}
65 chars
5 lines
  1. Next, create a database with a single user:
main.go
var user = User{
    Username: "myuser",
    PasswordHash: []byte("$2a$04$/qY8DflQ2Gh4rr41A2zmteX.N8hzs/LsSKPeT"),
} // The hashed password is "password"
154 chars
5 lines

Note: The above password hash is generated using bcrypt.

  1. Create a function to authenticate a user:
main.go
func authenticate(username, password string) bool {
    if username != user.Username {
        return false
    }
    err := bcrypt.CompareHashAndPassword(user.PasswordHash, []byte(password))
    return err == nil
}
216 chars
8 lines
  1. Create a middleware to handle authentication for protected routes:
main.go
func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        username, password, _ := r.BasicAuth()
        if !authenticate(username, password) {
            w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
            w.WriteHeader(http.StatusUnauthorized)
            w.Write([]byte("Unauthorized.\n"))
            return
        }
        next.ServeHTTP(w, r)
    })
}
463 chars
13 lines
  1. Use the middleware to protect specific routes:
main.go
func main() {
    r := mux.NewRouter()

    protectedRoute := r.PathPrefix("/protected").Subrouter()
    protectedRoute.Use(authMiddleware)
    protectedRoute.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Protected Content"))
    })

    http.ListenAndServe(":8080", r)
}
313 chars
12 lines

The above example shows the basic structure for an authentication system utilizing middleware in Go. This is just a starting point and there are many ways to further enhance the security of your authentication system.

gistlibby LogSnag