JWT Authentication in Golang

Explanation of JWT Authentication in Golang using Gin Web Framework

Introduction

Do you know, How to create a JWT Authentication Application in Golang using Gin Web Framework? If not!! Then no worries, you clicked the right content. In this tutorial, I will give you some idea about JWT Authentication with an example code. This blog will also cover an explanation regarding some concepts that are required to create a JWT Authentication App in Golang. But before proceeding the first thing that, I will mention is the prerequisites part that you need to have the knowledge of and the second thing is What exactly JWT Authentication is in Golang web development.

Prerequisites

You should be aware of the below-mentioned concepts so that you can understand the tutorial and get a proper learning outcome from it.
● You should know how to set up a workspace for your project. If you don’t know about it you can refer to this page.
● You should know what are the commands and processes to import mod files and other external packages.
● You should know the concept of Struct.
● You should know about Routing and concepts like API.
● Downloads

1) Go Programming Language
2) IDE (VS CODE)
3) PostMan Application

JWT Authentication

Let’s start with a definition of JWT Authentication. JWT is an abbreviation for JSON web token, which is a token-based stateless authentication method. It is frequently used as a client-side stateless session, allowing the server to save session data without relying entirely on a database. JWT is most commonly used in server-to-server authorization and API authentication.

Integration of JWT

Hereafter creating the directory on our command prompt, I will start building the Application to explain how you can create JWT Authentication Application. I hope you know about the command “code.” which will open up the IDE on your screen. Here the first file with which we will begin is main.go. In that main.go file I will import some internal packages like “log” and “os”. And some external packages are also required to be imported like github.com/gin-gonic/gin” (Gin), “github.com/golangcompany/JWT-Authentication/routes” (routes), and “github.com/joho/godotenv. Then after importing the packages, I will move ahead with my main.go function which includes the entry point of the program and it’s executed when you run your application. We’re using

if port == "" {port = "8000"}

to set a default value for the port. If the environment variable PORT is not set, we’ll use 8000 as the default value. Here, “routes.AuthRoutes(router)” and “routes.UserRoutes(router)” call the functions AuthRoutes and UserRoutes from the package routes. The function takes in an argument of type *gin.Engine, which is a pointer to a struct called Engine that belongs to the package gin. Then we state a simple API that returns JSON data that has two endpoints: /api-1 and /api-2. Finally, we instruct the program to start the server with router.Run(“:” + port). This is how you will proceed with the main.go file. (Refer to Image 1)

[Image 1]
I will next move on to creating a struct but before that let me give you an idea through an image of what folders and files you need to create in order to structure your program and execute it as expected. Please refer to image 2.

Now, let’s proceed towards struct. Here, my struct will carry different fields like ID, First Name, Last Name, Password, E-Mail, Phone Number, Token ID, User Type, Refresh Token ID, Created at, Updated at, and User ID. I have the primitive package in my models since, I want that for every user, who gets registered gets a unique ID in my database so that while fetching the users, I can use that ID to fetch the user without any conflicts. I used “validate”, which checks if the data entered from the client side is in the format we’ve programmed for and returns an error if it isn’t. In the User type field, I mentioned eq=ADMIN|eq=USER because it validates the value of the field user type to be either ADMIN or USER. I will now guide you on the routes folder.

[Image 2]
[Image 3]
[Image 4]
[Image 5]
Here in routes, I have created two files i.e., authRouter.go and userRouter.go. Where in authRouter.go includes a function that sets up the routes for our application. It takes in an instance of gin.Engine and adds two routes to it: one for signup and one for login. And userRouter.go states a function that takes in an object of type *gin.Engine and returns nothing. It adds two routes to the incomingRoutes object: /users and /users/:user_id. The first route will call the GetUsers() function from the controller package, while the second route will call the GetUser() function from the controller package (Refer to Images 4 & 5). Now we need to work on our MongoDB connection for which you can refer to my other blog. After the Database setup, I will explain about middlewares and controllers. (Refer to Image 6).

[Image 6]
Middleware contains an Authentication function that checks if the request has a token in its header. If it does, it validates the token and sets some values to the context. This code has 4 imports and they are “fmt”, “github.com/gin-gonic/gin”, “github.com/golangcompany/JWT-Authentication/helpers” (helper), and “net/http”. Please refer to above code for more information on the code. After middleware, here come the controllers where we have userController.go where we have imported mongo driver, validator, gin, and some other packages for which you can refer to image 7.

[Image 7]
[Image 8]
This is a variable declaration. It declares a variable with the identifier userCollection and assigns it the value of the database.UserData(database.Client, “user”). The type of this variable is *mongo.Collection. The function database.UserData() returns a pointer to a mongo collection object (which is why we use the asterisk). This object represents the user collection in our database, which contains all users’ data. The second line declares another variable called validate, which has been assigned the value returned by calling the function validator.New(). The type of this variable is also a pointer to an object: *validator.Validate. Next, I have stated the functions, The first function i.e., HashPassword takes in a string and returns a string. It hashes the password using bcrypt.GenerateFromPassword() and returns the hashed password as a string (Refer to Image 9). Then I stated the VerifyPassword function that verifies the password. It takes two parameters, the userPassword, and providedPassword. The function returns a boolean value and a string (Refer to image 10). Next comes the SignUp function that creates a user. It takes in the user’s details, validates them, and then stores them in the database (Refer to Image 11). Simultaneously, I have mentioned the Login function which handles a user’s login with its ID and Password (Refer to Image 12). Finally, I have worked on the last two functions i.e., GetUsers and GetUser. Here, GetUsers is a function that will list all users in the database and return them to the client and GetUser is a function that will list users by their ID and return them to the client (Refer to Images 13 & 14).

[Image 9]
[Image 10]
[Image 11]
[Image 12]
[Image 13]
[Image 14]
In the final steps, I have created two files in helper i.e., authHelper.go and tokenHelper.go in which authHelper.go contains two functions. The first function, CheckUserType, determines whether or not the user type matches the role. The second function, MatchUserTypeToUid, determines whether the user id matches the context uid. And tokenHelper.go contains functions to generate, validate and update JWT tokens (Refer to Images 15 – 19). This is how you can create your JWT Authentication App in Golang using Gin Web Framework. And finally, to test it you can use the Postman Application to test your application.

[Image 15]
[Image 16]
[Image 17]
[Image 18]
[Image 19]
11 Shares: