Search⌘ K
AI Features

Middleware Creation for GraphQL

Explore the process of building middleware in Go for GraphQL applications. Understand how to extract, verify, and validate JWT tokens to ensure secure authentication in your backend services. This lesson guides you through creating helper functions and middleware components that manage token metadata and user context, enabling authenticated requests.

We'll cover the following...

Add a middleware

Before creating a middleware, we create some additional helpers in the auth.go file. These helpers verify the JWT token.

We add a helper function called ExtractTokenMetadata inside auth.go in the utils directory.

Go (1.18.2)
package utils
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
)
// TokenMetadata represents JWT token metadata
type TokenMetadata struct {
Expires int64
UserId string
}
// ExtractTokenMetadata extracts JWT token metadata
func ExtractTokenMetadata(r *http.Request) (*TokenMetadata, error) {
// verify the JWT token
token, err := verifyToken(r)
// if verification is failed, return an error
if err != nil {
return nil, err
}
// get a JWT claim from the JWT token
claims, ok := token.Claims.(jwt.MapClaims)
// check if the token is valid
var isValid bool = ok && token.Valid
// if the JWT token is valid, return the JWT token metadata
if isValid {
// set token expiration
expires := int64(claims["exp"].(float64))
// set user ID for the token
userId := claims["userId"].(string)
// return the JWT token metadata
return &TokenMetadata{
Expires: expires,
UserId: userId,
}, nil
}
// return an error
return nil, err
}
Function to extract the JWT token metadata

Below is an explanation of the code above:

  • In lines 13-16, the TokenMetadata struct is created to store the JWT token metadata.

  • In line 21, the JWT token is verified.

  • In line 29, the claim of the JWT is extracted.

  • In line 32, the JWT token is validated.

  • In line 35, the JWT token is checked to ensure the token is valid.

  • In line 37, the JWT ...