Echo: cors middleware: set `AllowOrigins` on the fly

Created on 19 Jun 2018  路  2Comments  路  Source: labstack/echo

Hello. I have the following configuration:

    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
        AllowCredentials: true,
        AllowMethods:     []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
        AllowOrigins:     []string{"*"},
    }))

But webpage gives me the following error:

Failed to load https://domain.xyz/v0/partners/test: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. 
Origin 'https://domain.missena.xyz' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Is there a way to set AllowOrigins on the fly by adding the current requesting domain?

Most helpful comment

Just in case anyone comes here looking for an answer to the original question. I figured it out...

func CORSMiddlewareWrapper(next echo.HandlerFunc) echo.HandlerFunc {
    return func(ctx echo.Context) error {
        req := ctx.Request()
        dynamicCORSConfig := middleware.CORSConfig{
            AllowOrigins: []string{req.Header.Get("Origin")},
            AllowHeaders: []string{"Accept", "Cache-Control", "Content-Type", "X-Requested-With"},
        }
        CORSMiddleware := middleware.CORSWithConfig(dynamicCORSConfig)
        CORSHandler := CORSMiddleware(next)
        return CORSHandler(ctx)
    }
}

// Then just add it to e.Use() as normal....

e.Use(
  .....
  CORSMiddlewareWrapper
)

All 2 comments

the issue happens when using AllowCredentials

Just in case anyone comes here looking for an answer to the original question. I figured it out...

func CORSMiddlewareWrapper(next echo.HandlerFunc) echo.HandlerFunc {
    return func(ctx echo.Context) error {
        req := ctx.Request()
        dynamicCORSConfig := middleware.CORSConfig{
            AllowOrigins: []string{req.Header.Get("Origin")},
            AllowHeaders: []string{"Accept", "Cache-Control", "Content-Type", "X-Requested-With"},
        }
        CORSMiddleware := middleware.CORSWithConfig(dynamicCORSConfig)
        CORSHandler := CORSMiddleware(next)
        return CORSHandler(ctx)
    }
}

// Then just add it to e.Use() as normal....

e.Use(
  .....
  CORSMiddlewareWrapper
)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

toorop picture toorop  路  4Comments

dre1080 picture dre1080  路  4Comments

asdine picture asdine  路  3Comments

neutronstein picture neutronstein  路  3Comments

leoycx picture leoycx  路  4Comments