Golang: How Setup Basic Authentication Middleware With Goloang Echo Framework

Lets implement basic auth middleware functionality into echo golang project

Authentication is the most fundamental building block of any application. Whenever we start building a new app, we consider how users authenticate in the very beginning. In the olden days, we used to implement session based authentication and transmitted the data using cookies. Using JSON Web Tokens can mitigate this issue. We don’t have to store any session data in our database or anywhere because JWTs can carry information with them in JSON format. Although they can be encrypted, we will be focusing on signed tokens which carry the authenticated user’s information.
I highly recommend going through the following writing to learn more about the structure of JWTs here
. . .
To get started, we need to create a new Go application:
Make the path appropriate for your workspace & install deps.
mkdir go-jwtgo get github.com/labstack/echo
go get github.com/dgrijalva/jwt-go
I will be using the Echo Framework. It’s a very minimalist framework which has the essentials baked in. Let’s create the main.go file by taking the code from the Echo Guide. This will be our starting point. main.go:

If you run the application now, echo fires up a server and listens on the :1323 port. A basic hello world application.
. . .

Let’s create the login handler

handler.go

Since database connection and querying is not in the scope of this article, I checked the username and password this way.

This is a very minimal application describing the core of JWT in Go.
We need to add a route for login:

Now run the app to test our login handler is working:
go run *.go
Test /login route
curl -X POST localhost:1323/login -d "username=jon&password=password"
Output:
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiZXhwIjoxNTQyNjkwMjQ3LCJuYW1lIjoiSm9uIERvZSJ9.OqsaJ76nYhiaiVPcAr13_vMPyTfRcv6eKFm06O3n8fE"}
You should get the token in the response when you hit the api with the correct username and password. Incorrect username and password will throw an unauthorised error.
curl -X POST localhost:1323/login -d "username=jon&password=nope"{"message":"Unauthorized"}
Since the token is being generated using exp (expiration), it will be unique everytime. Let’s inspect how our token looks when decoded, head over to jwt.io and paste the token: Header:
{ "alg": "HS256", "typ": "JWT" }
Payload:
{ "admin": true, "exp": 1542690247, "name": "Jon Doe" }
Both front and backend can use the payload to identify the user.
. . .

Never miss a post from Chris Gregori, when you sign up for Ednsquare.