Home > database >  how to pass parameter of the destination to middleware in gin/golang
how to pass parameter of the destination to middleware in gin/golang

Time:08-25

My problem in short is: I send my auth token as a parameter to my destination api and it seems like middleware can not access that. How can I access the parameter since the middleware needs that to check the auth conditions?

I am trying to implement a simple authentication/authorization application. I know that it is common to set auth token in coockies, however, in my use-case, I need it to be implemented differently.

The implementation is: login returns auth token in response body and anytime authentication token is required, it is sent as a parameter "authorization" to the application.

here is the code for my user routers :

func UserRoute(router *gin.Engine) {
    user := router.Group("/user")
    {
        user.POST("/signup", controllers.SignUp)
        user.POST("/login", controllers.Login)

        user.GET("/validate", middleware.RequireAuth, controllers.Validate)
    }
}

validate function in usercontrollers.go:

func Validate(c *gin.Context) {
    user, _ := c.Get("user")
    c.IndentedJSON(http.StatusOK, gin.H{
        "message": user,
    })
}

here is the request I send

http://localhost:6000/user/validate?authorization=[My-JWT-Token]

Now when I try to read my auth parameter and use it in my middleware it seems like it does not actually exist:

func RequireAuth(c *gin.Context) {
    confs, _ := configs.LoadConfig()
    tokenString := c.Param("authorization")

    if tokenString == "" {
       // this abort case always happens
       c.AbortWithStatus(http.StatusUnauthorized)
    }
}

CodePudding user response:

1. ctx.Request.URL.Query().Get("authorization")
2. ctx.Query("authorization")
  • Related