英文:
How can we reach claims in fiber.context custom middleware?
问题
我想将声明设置为fiber.context。但是在第3行中出现了错误,错误是*jwt.Token为空。我如何获取token或claims?或者你有其他建议要使用什么。
func RoleMiddleware() func(*fiber.Ctx) { //更改名称
return func(ctx *fiber.Ctx) {
user := ctx.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
ctx.Locals("id", int(claims["id"].(float64)))
ctx.Locals("is_api", claims["is_api"])
ctx.Locals("is_admin", claims["is_admin"])
ctx.Locals("is_super_admin", claims["is_super_admin"])
}
}
我将在我的user_controller中使用这个示例:
user_id := ctx.Locals("id").(int)
英文:
I want to set claims to fiber.context. But I got an error in 3th line that is *jwt.Token is empty. How can I reach token or claims ? Or do you have an advice to use anything else.
func RoleMiddleware() func(*fiber.Ctx) { //change name
return func(ctx *fiber.Ctx) {
user := ctx.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
ctx.Locals("id", int(claims["id"].(float64)))
ctx.Locals("is_api", claims["is_api"])
ctx.Locals("is_admin", claims["is_admin"])
ctx.Locals("is_super_admin", claims["is_super_admin"])
}
}
I will use this for example in my user_controller:
user_id := ctx.Locals("id").(int)
答案1
得分: 1
你可以在 gofiber recipes 仓库中找到一个完整的 JWT 示例实现。
链接:https://github.com/gofiber/recipes/tree/master/jwt
简而言之:
product := api.Group("/product")
product.Get("/", handler.GetAllProducts)
product.Get("/:id", handler.GetProduct)
product.Post("/", middleware.Protected(), handler.CreateProduct)
product.Delete("/:id", middleware.Protected(), handler.DeleteProduct)
请确保在每个受保护的路由上使用与示例中完全相同的过滤器:
使用 middleware.Protected()
,这样 JWT 令牌就可以在你的处理程序的 ctx.Locals
中使用了。
英文:
You have a complete JWT exmaple implementation in gofiber recipes repo.
link: https://github.com/gofiber/recipes/tree/master/jwt
In short.
product := api.Group("/product")
product.Get("/", handler.GetAllProducts)
product.Get("/:id", handler.GetProduct)
product.Post("/", middleware.Protected(), handler.CreateProduct)
product.Delete("/:id", middleware.Protected(), handler.DeleteProduct)
- Make sure you're using the filter on each protected route exactly as in the example:
Properly with middleware.Protected()
so JWT token should be available in your handler ctx.Locals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论