Authentication middleware not working in Gin

Viewed 1134

I have the following routes and the session setup:

func SetupRouter() *gin.Engine {
    r := gin.Default()

    // Session
    store := cookie.NewStore([]byte("secret"))
    // Set session expiration time
    store.Options(sessions.Options{MaxAge: 3600 * 24}) // 24hr
    r.Use(sessions.Sessions("mysession", store))

    r.GET("api/business/", controllers.GetBusiness)
    r.POST("api/business/login", controllers.Login)
    r.GET("api/business/logout", controllers.Logout)
    r.GET("api/business/session", controllers.GetBusinessSession)
    r.POST(
        "api/itemcategory/add", 
        // isBusinessAuth(), 
        controllers.CreateItemCategory,
    )
    r.POST(
        "api/itemcategory/delete/:id",
        // isBusinessAuth(),
        controllers.DeleteItemCategory,
    )
    r.GET(
        "api/itemcategory/all",
        // isBusinessAuth(),
        controllers.GetAllItemCategories,
    )
    r.POST(
        "api/itemcategory/update/:id",
        // isBusinessAuth(),
        controllers.CreateItemCategory,
    )

    return r
}

the isBusinessAuth() function:

func isBusinessAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        if sessions.Default(c).Get("businessAuth") == 1 {
            c.Next()
            return
        } else {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "You are not authorized!"})
        }
        c.Abort()
        return
    }
}

This is how session is placed, in the Login function:

// Set business session
session.Set("businessAuth", 1)
session.Save()

No matter what value has the session, isBusinessAuth() is returning "You are not authorized" for all the routes where is used. I tried to put it on "/api/business/login" and "/api/business/session" routes and there is working as expected. What am I missing?

Thank you :)

1 Answers

This requires the client to be able to save cookies, which you can test using Chrome

Session communication is generally realized through cookie. Different from cookie, session only saves a sessionID on the client. Unlike cookie, specific data of session is only saved on the server instead of the client

In Servlet, session data is encapsulated in an object, which will be stored in the object pool. When the client makes a request, it will bring its sessionID, and the server will obtain the corresponding session object from the object pool according to this sessionID. Obtains session data from the object. The server uses this session data to maintain or change the state of the session with the client.

When accessing the server, the client checks whether the client request data contains a SessionID. If not, the client is considered to be accessing the server for the first time

Related