PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

[FIXED] how to pass parameter of the destination to middleware in gin/golang

 September 02, 2022     authentication, go, jwt     No comments   

Issue

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)
    }
}

Solution

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


Answered By - Guolei
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing