It doesn't work by just simply add Use in context
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
//"github.com/labstack/echo/engine/fasthttp"
"github.com/labstack/echo/middleware"
)
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.Gzip())
e.Use(middleware.CSRF([]byte("secret")))
e.GET("/", form)
e.POST("/", formPost)
// Start server
e.Run(standard.New(":1324"))
}
func form(c echo.Context) error {
return c.HTML(http.StatusOK, `
<html>
<body>
<form method='POST'>
<input type='text' name='name' /><br/>
<input type='submit' value='submit' />
</form>
</body>
</html>
`)
}
func formPost(c echo.Context) error {
name := c.FormValue("name")
return c.String(http.StatusOK, name)
}
And error shows
invalid csrf token
You have to send CSRF token back. It can be read from cookie? Default CSRF middleware looks for CSRF token in header key X-CSRF-Token.
I see. I checked code, and learnt it like what you mentioned.
While since by default it writes to cookie, is there any concern that not read from cookie directly?
I will update the docs but you should look into in general how to use CSRF.
I see, Thanks.
@vishr, I believe this ticket can be closed?
For others, searching for information on how to use CSRF protection:
csrf and the value of csrf token.go
api.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
TokenLookup: "form:csrf",
}))
echo#Context: csrf_value := ctx.Get(middleware.DefaultCSRFConfig.ContextKey).(string)If you need to protect other methods, you will probably need a different configuration and passing the token through HTTP headers.
Thanks @skyflyer
Most helpful comment
@vishr, I believe this ticket can be closed?
For others, searching for information on how to use CSRF protection:
csrfand the value of csrf token.go api.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{ TokenLookup: "form:csrf", }))echo#Context:csrf_value := ctx.Get(middleware.DefaultCSRFConfig.ContextKey).(string)If you need to protect other methods, you will probably need a different configuration and passing the token through HTTP headers.