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)
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)
Properly with middleware.Protected()
so JWT token should be available in your handler ctx.Locals