Golang: Gin middleware for authentication

Golang: Gin middleware for authentication

ยท

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 !