英文:
how to pass parameter of the destination to middleware in gin/golang
问题
我的问题简而言之是:
我将我的身份验证令牌作为参数发送到目标 API,但似乎中间件无法访问该参数。我该如何访问该参数,因为中间件需要检查身份验证条件?
我正在尝试实现一个简单的身份验证/授权应用程序。
我知道通常会将身份验证令牌设置在 cookie 中,但在我的用例中,我需要以不同的方式实现它。
实现方式是:登录返回响应体中的身份验证令牌,每当需要身份验证令牌时,将其作为参数“authorization”发送到应用程序。
这是我的用户路由器的代码:
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)
}
}
usercontrollers.go
中的 validate
函数:
func Validate(c *gin.Context) {
user, _ := c.Get("user")
c.IndentedJSON(http.StatusOK, gin.H{
"message": user,
})
}
这是我发送的请求:
http://localhost:6000/user/validate?authorization=[My-JWT-Token]
现在,当我尝试读取我的身份验证参数并在中间件中使用它时,似乎它实际上并不存在:
func RequireAuth(c *gin.Context) {
confs, _ := configs.LoadConfig()
tokenString := c.Param("authorization")
if tokenString == "" {
// 这种中止情况总是发生
c.AbortWithStatus(http.StatusUnauthorized)
}
}
英文:
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)
}
}
答案1
得分: 2
- ctx.Request.URL.Query().Get("authorization"):获取ctx请求中的URL查询参数中名为"authorization"的值。
- ctx.Query("authorization"):获取ctx请求中名为"authorization"的查询参数的值。
英文:
1. ctx.Request.URL.Query().Get("authorization")
2. ctx.Query("authorization")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论