How to use Middleware handler
vibhuh opened this issue · comments
Murugesan commented
Question Description
Middleware in the handler is not working as expected.
Code Snippet (optional)
package main
import (
"crypto/sha256"
"crypto/subtle"
"fmt"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/keyauth"
)
var (
apiKey = "correct horse battery staple"
)
func validateAPIKey(c fiber.Ctx, key string) (bool, error) {
hashedAPIKey := sha256.Sum256([]byte(apiKey))
hashedKey := sha256.Sum256([]byte(key))
if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 {
fmt.Println("checkpoint: 14-April-2024: _____________--_______-______- validateAPIKey -______--_________--")
return true, nil
}
fmt.Println("checkpoint: 14-April-2024: _____________--_______-______- validateAPIKey false -______--_________--")
return false, keyauth.ErrMissingOrMalformedAPIKey
}
func AuthMiddleWare() fiber.Handler {
fmt.Println("checkpoint: 14-April-2024: _____________--_______-______- AuthMiddleWare -______--_________--")
return keyauth.New(keyauth.Config{
//Next: authFilter,
KeyLookup: "cookie:access_token",
Validator: validateAPIKey,
})
}
func Profile(ctx fiber.Ctx) error {
return ctx.Status(fiber.StatusOK).JSON(SuccessResponseStringData("User info"))
}
func SuccessResponseStringData(message string) *fiber.Map {
return &fiber.Map{
"status": "success",
"error": false,
"message": message,
}
}
func main() {
app := fiber.New()
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Welcome")
})
app.Get("/authenticated", AuthMiddleWare(), Profile)
app.Listen(":3000")
}
Checklist:
- I agree to follow Fiber's Code of Conduct.
- I have checked for existing issues that describe my questions prior to opening this one.
- I understand that improperly formatted questions may be closed without explanation.
welcome commented
Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord
Juan Calderon-Perez commented
@vibhuh This is a bug in the documentation,
// v2
func (app *App) Get(path string, handlers ...Handler) Router
// v3
func (app *App) Get(path string, handler Handler, middleware ...Handler) Router
Try changing this line:
-> app.Get("/authenticated", AuthMiddleWare(), Profile)
To this line:
-> app.Get("/authenticated", Profile, AuthMiddleWare)
Juan Calderon-Perez commented
@vibhuh Does that solve your issue?