Middleware Creation for GraphQL
Learn how to create a middleware for the GraphQL application.
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.
package utilsimport ("net/http""strconv""strings""time""github.com/golang-jwt/jwt/v4")// TokenMetadata represents JWT token metadatatype TokenMetadata struct {Expires int64UserId string}// ExtractTokenMetadata extracts JWT token metadatafunc ExtractTokenMetadata(r *http.Request) (*TokenMetadata, error) {// verify the JWT tokentoken, err := verifyToken(r)// if verification is failed, return an errorif err != nil {return nil, err}// get a JWT claim from the JWT tokenclaims, ok := token.Claims.(jwt.MapClaims)// check if the token is validvar isValid bool = ok && token.Valid// if the JWT token is valid, return the JWT token metadataif isValid {// set token expirationexpires := int64(claims["exp"].(float64))// set user ID for the tokenuserId := claims["userId"].(string)// return the JWT token metadatareturn &TokenMetadata{Expires: expires,UserId: userId,}, nil}// return an errorreturn 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 ...