使用Echo框架进行基本身份验证

时间:2020-05-10 22:51:53

标签: go

尝试使用Go的Echo框架使基本身份验证正常工作。到目前为止,已经找到了几段代码,但还没有完整的代码集。

到目前为止,这个基本程序已经完成

package main

import (
    "github.com/labstack/echo"
   "github.com/labstack/echo/middleware"
    "net/http"
)

func main() {
  var html string;
    // Echo instance
    e := echo.New()

    // Route => handler
    e.GET("/", func(c echo.Context) error {

  e.Group("/").Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
    if username == "user" && password == "password" {
      html ="Authenticated"
      return true, nil
    }
    return false, nil
}))


        return c.HTML(http.StatusOK, html)
    })

    // Start server
    e.Logger.Fatal(e.Start(":1323"))
}

它提示您输入用户名和密码,但是经过身份验证后,我得到了

“未找到”消息

希望使用Echo框架的基本身份验证提供任何建议或链接到工作代码。

2 个答案:

答案 0 :(得分:2)

除了fstanis回答here之外,我想指出的是,您在参考回显组对象时应格外小心。

所以我认为您应该这样做

e := echo.New()
g := e.Group("")
g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
  if username == "joe" && password == "secret" {
    return true, nil
  }
  return false, nil
}))

// note that it was previously referring to the echo instance, not group.
g.GET("/", func(c echo.Context) error {
    return c.HTML(http.StatusOK, html)
})

请注意,g指向组e.Group(""),这确保GET“ /”的处理程序将返回正确的html。因此,对于将基本身份验证中间件应用于组还是Echo e的根实例,没有任何疑问。

答案 1 :(得分:0)

您正在路由的回调内注册Group。相反,您想在顶层注册组并为其添加路由:

e := echo.New()
g := e.Group("")
g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
  if username == "joe" && password == "secret" {
    return true, nil
  }
  return false, nil
}))
e.GET("/", func(c echo.Context) error {
    return c.HTML(http.StatusOK, html)
})
相关问题