Search⌘ K
AI Features

Middleware Creation for REST API

Understand how to develop middleware for REST API in Go that handles JWT-based authentication. Learn to create helper functions for token extraction and validation, implement middleware checks, and group routes into public and private sets to manage access control for your backend application efficiently.

We'll cover the following...

Add middleware

Middleware is a component that acts as an interceptor for the request before another request has proceeded. For example, the middleware is added to create a new item request. In this example, the middleware acts as authentication to ensure the authenticated user can create a new item request.

Inside the auth.go file in the utils directory, we add some helpers for authentication purposes.

Before the GenerateNewAccessToken() function, we add a struct for storing the JWT token’s metadata.

type TokenMetadata struct {
	Expires int64
}

After the GenerateNewAccessToken() function, we create a helper function called ExtractTokenMetadata.

Go (1.18.2)
// ExtractTokenMetadata returns token metadata
func ExtractTokenMetadata(c *fiber.Ctx) (*TokenMetadata, error) {
// verify the token
token, err := verifyToken(c)
// if verification is failed, return an error
if err != nil {
return nil, err
}
// get the token claim data
claims, ok := token.Claims.(jwt.MapClaims)
// if token claim data exists and token is valid
if ok && token.Valid {
// set the token expiration date
expires := int64(claims["exp"].(float64))
// return the token metadata
return &TokenMetadata{
Expires: expires,
}, nil
}
// return an error if token is invalid
return nil, err
}
Function to create token metadata from the valid JWT token

In the code above, the ExtractTokenMetadata() function is used to extract the token metadata.

We then create a function called CheckToken ...