Francisco1844
Francisco1844

Reputation: 1218

Go basic authentication with Echo framework

Trying to get basic authentication to work using the Echo framework for Go. Have found several snippets of code, but not a complete set of code so far.

Have this basic program so far

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"))
}

It prompts for user and password, but after authentication I get

message "Not Found"

Would appreciate any suggestions or link to working code using the basic authentication of the Echo framework.

Upvotes: 1

Views: 5531

Answers (2)

Albert Putra Purnama
Albert Putra Purnama

Reputation: 29

On top of what fstanis answered here, I would like to point out that you should be careful on the reference of the object of echo group.

So I think you should do this instead

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)
})

Note that g refers to to the group e.Group(""), This ensures that the handler for GET "/" will return the correct html. Thus leaving no ambiguity on whether basic authentication middleware is applied on the Group or the root instance of Echo e.

Upvotes: 2

fstanis
fstanis

Reputation: 5554

You're registering a Group inside a callback for your route. Instead, you want to register group(s) at the top level and add routes to them:

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)
})

Upvotes: 0

Related Questions