GoFiber 为共享相同基本路由的组提供不同的中间件

问题描述 投票:0回答:1
func GetRouter() *fiber.App {
    app := fiber.New()

    public_group := app.Group("/")
    public_group.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World 👋!")
    })

    public_group.Post("/register", handlers.RegisterUser)
    public_group.Post("/login", handlers.AuthenticateUser)
        ...

    auth_group := app.Group("/", middleware.AuthRequired)
    auth_group.Get("/auth/me", handlers.GetUser)
    auth_group.Put("/auth/me", handlers.UpdateUser)
    auth_group.Post("/auth/me/password", handlers.UpdatePassword)
...

代码应该已经传达了这一点,但同样,我有一些公共路由和一些我想强制执行身份验证中间件的路由。现在,当我尝试访问

/
路线,期待“hello world”响应时,我得到的是:(由服务器记录)

auth middleware engaged
[ 2023-12-18 16:22:41 ] GET /v0 | 127.0.0.1 - ✗ Authorization header does not exist
Response: 200 [took 337.709µs]
{
  "message": "authorization header required to access this endpoint",
  "status": 401
}

身份验证中间件一开始就不应该在这里使用!这是身份验证中间件(如果有帮助的话):

package middleware

import (
    responses "backend/models/api/responses"
    "backend/utils"
    "fmt"

    fiber "github.com/gofiber/fiber/v2"
)

func AuthRequired(c *fiber.Ctx) error {
    fmt.Println("auth middleware engaged")
    auth_header := c.Get("Authorization")
    if auth_header == "" {
        return c.JSON(responses.BaseResponse{
            Status:  401,
            Message: "authorization header required to access this endpoint",
        })
    }
    if _, err := utils.ValidateJWT(auth_header); err != nil {
        return c.JSON(responses.BaseResponse{
            Status:  401,
            Message: "invalid authorization header",
        })
    }
    return c.Next()
}

此外,当前代码的灵感来自于类似查询的答案

我不想使用不同的基本路线。目前,这解决了问题,但我仍然想知道如何做我最初想做的事情

    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World 👋!")
    })

    app.Post("/auth/register", handlers.RegisterUser)
    app.Post("/auth/login", handlers.AuthenticateUser)

    accounts_route := app.Group("/accounts", middleware.AuthRequired)

    accounts_route.Get("/me", handlers.GetUser)
    accounts_route.Put("/me", handlers.UpdateUser)
    accounts_route.Post("/me/password", handlers.UpdatePassword)
    ...
go middleware go-fiber
1个回答
0
投票

您正在有效地将 middleware.AuthRequired 中间件应用到根路径 ("/"),其中包括此行之后定义的所有路由。这意味着中间件也应用于您的公共路由,因此 "/" 路由需要意外的身份验证要求。你可以试试这个:

auth_group := app.Group("/auth", middleware.AuthRequired)
© www.soinside.com 2019 - 2024. All rights reserved.