gin-contrib / cors

Official CORS gin's middleware
https://gin-gonic.github.io/gin/
MIT License
1.76k stars 182 forks source link

repeated response headers in cors setup of gin proxy server and a gin server #154

Open catosaurusrex2003 opened 1 month ago

catosaurusrex2003 commented 1 month ago

The Problem

i am getting a response like this image the problem with this response is that it has access-control-allow-origin: * 2 times.

this raises a CORS error from the browser https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSAllowOriginNotMatchingOrigin "This error can also occur if the response includes more than one Access-Control-Allow-Origin header." this line is taken from the docs above 👆

image

the request is succeeding with status code 200 but the browser doesn't allow the access of the response due to inconsistent response headers

What is Happening

i have a proxy server made in gin and using this library for cors this proxy server calls another gin server which is also using this library for cors

the way i am setting the cors in both the server is same

func ConfigureServer() {
    // configure gin server
    gin.DefaultWriter = io.MultiWriter(os.Stdout)
    if viper.GetString("APP_ENV") == "production" {
        gin.SetMode(gin.ReleaseMode)
    }
    AppConfig.Router = gin.Default()
    AppConfig.Router.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"*"},
        AllowMethods:     []string{"GET", "POST", "PATCH", "PUT"},
        AllowHeaders:     []string{"Content-Type", "x-trace-id", "Authorization"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
    }))
}

FINAL

is this a issue in this library or is it a problem in my implementation

i think there should be a check somewhere which prevents from setting same header twice

below is the code for the proxy server for reference

func (fh *FinancierHandler) ProxyRequestHandling(c *gin.Context) {

    remote, err := url.Parse(constants.GetFinancierServiceUrl())
    if err != nil {
                // handle the error
        return
    }

    proxy := httputil.NewSingleHostReverseProxy(remote)
    originalDirector := proxy.Director
    proxy.Director = func(req *http.Request) {
        originalDirector(req)
        req.Header = c.Request.Header
        req.Host = remote.Host
        req.URL.Scheme = remote.Scheme
        req.URL.Path = constants.ROUTE_API_V1 + c.Param("proxyPath")
        req.URL.Host = remote.Host
    }

    proxy.ServeHTTP(c.Writer, c.Request)
}
korebhaumik commented 1 month ago

I was facing a similar issue thanks cato for bringing this into attention.