我们如何在fiber.context自定义中间件中访问声明?

huangapple go评论78阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年8月7日 00:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73261520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定