Golang: Gin middleware for authentication

Dhairya VermaDhairya Verma
1 min read

In this blog, we will delve into gin middleware to authorize the user access Token.

    sampleRoute := router.Group("/sample")
    // we are telling gin to use TokenAuthMiddleware
    // for all requests with path /sample/*
    sampleRoute.Use(middlewares.TokenAuthMiddleware())
    {
        sampleRoute.GET(
            "get",
            controllers.GetSampleData,
        )
    }

Now, let's write the code for middleware that authorizes all requests. Here in this code, we will read the auth token from the headers, find the user corresponding to that auth code, and pass it to the main handler. I am using gorm for accessing user data.

func TokenAuthMiddleware() gin.HandlerFunc {

    return func(c *gin.Context) {
        /// reading auth token
        accessToken := c.Request.Header.Get("Authorization")

        var user db.User
        if err := store.Postgres.Where(&db.User{AuthToken: accessToken}).First(&user).Error; err != nil {
            resp := api.Response{
                StatusCode: http.StatusUnauthorized,
                Message:    "Auth token is invalid",
                Success:    false,
            }
            resp.SendResponse(c)
            return
        } else {
            // we have added the user to context
            c.Set("user", user)
        }
        c.Next()
    }
}

Let's see how we access the user from handler

func GetSampleData(c *gin.Context) {    
    // now we have the user
    user, _ := c.Get("user")
    u := user.(db.User)
    // .....
}

Happy Coding !

0
Subscribe to my newsletter

Read articles from Dhairya Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhairya Verma
Dhairya Verma

Hey there ๐Ÿ‘‹ I'm Dhairya, a backend developer. With a solid background spanning 5 years, my achievement includes scaling an app to 3M users.