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.
In the code above, the ExtractTokenMetadata() function is used to extract the token metadata.
We then create a function called CheckToken ...