BasicAuth Middleware With Go Echo Framework

BasicAuth Middleware With Go Echo Framework

This is another golang tutorial for the echo web framework. I am implementing basicauth middle-ware functionality into echo golang projects.ECHO Framework is providing many middlewares that supports logger, recover, JWT and basichAuth. You can call Middleware with routes or groups.

This golang tutorial uses BasicAuth into rest APIs or group of rest api.

You can also check other recommended tutorials of golang,

  • Getting Started with GoLang
  • Creating a Go(lang) API with Echo Framework and PostgreSQL
  • Building GoLang Restful API Using Echo and MySQL
  • How to Write Log into Files in Go/Golang

Let’s Implement BasicAuth Middleware

I am assuming, You have created golang application and used Echo. We will create an echo golang instance,

e := echo.New()
e.Use(middleware.Logger())

Logger() is used to log messages, I am using Logger middleware as well, you can remove this line if you don’t want logs.

We will create versioning of API with groups,

//define api version
v1 := e.Group("/api/v1")

Where 'e' is the echo instance variable.

Now we will use middleware with echo instance and passed ValidateUser method for validating user credentials using BasicAuth.

//added middleware
v1.Use(middleware.BasicAuth(helper.ValidateUser))

We will create auth.go file and add ‘helper’ a package name. We will define ValidateUser method here.

package helper
 
import (
   "net/http"
   "fmt"
   "github.com/labstack/echo"
   "github.com/spf13/viper"
)
 
func ValidateUser(username, password string, c echo.Context) (bool, error) {
      if username == "joe" && password == "secret" {
                                return true, nil
                }
                return false, nil
}

We have imported all required packages and created a method ValidateUser() with username and password parameters, that will pass from the user side.

Now we will create the rest endpoint to validate whether middleware is working or not, if it’s working then get true otherwise false.

The ValidateUser() methods will call on each request of v1 groups.