Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

it doesn't work #148

Open
douno23 opened this issue Apr 13, 2024 · 14 comments
Open

it doesn't work #148

douno23 opened this issue Apr 13, 2024 · 14 comments

Comments

@douno23
Copy link

douno23 commented Apr 13, 2024

here is the code:

package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func main() {
	router := gin.Default()
	// CORS for https://foo.com and https://github.com origins, allowing:
	// - PUT and PATCH methods
	// - Origin header
	// - Credentials share
	// - Preflight requests cached for 12 hours
	router.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"https://foo.com"},
		AllowMethods:     []string{"PUT", "PATCH"},
		AllowHeaders:     []string{"Origin", "token"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowOriginFunc: func(origin string) bool {
			return origin == "https://github.com"
		},
		MaxAge: 12 * time.Hour,
	}))
	router.GET("/", func(context *gin.Context) {
		context.String(http.StatusOK, "hello world")
	})
	router.Run()
}

browser response:
image

postman response
image

can not find Access-Control-Allow-Origin Access-Control-Expose-Headers and so on

@klm127
Copy link

klm127 commented Apr 17, 2024

When you use AllowOriginFunc, AllowOrigins is ignored. So you should remove AllowOrigins and put the foo.com check inside of AllowOriginFunc, eg:

AllowOriginFunc: func(origin string) bool {
			if origin == "http://www.foo.com" {
				return true
			}
			if origin == "https://github.com" {
				return true
			}
			return false
		}

I noticed that foo.com, if you are actually testing there, is not secure, so make sure it's http not https.

Secondly, github.com has a content security policy that prevents CORs requests, so it may not be a simple matter to query your server from the dev console, for example.

@douno23
Copy link
Author

douno23 commented Apr 17, 2024

AllowOriginFunc: func(origin string) bool {
			if origin == "http://www.foo.com" {
				return true
			}
			if origin == "https://github.com" {
				return true
			}
			return false
		}

i have tried this, but doesn't work either.

@jub0bs
Copy link

jub0bs commented Apr 23, 2024

@douno23 The screenshot you shared shows a request that does not include any Origin header; therefore, it's not a CORS request.

@go-english
Copy link

i have the same problem

@jub0bs
Copy link

jub0bs commented Apr 25, 2024

@go-english What problem? If the request doesn't contain any Origin header, it doesn't participate in the CORS protocol and you cannot expect it to contain CORS response headers (though it could, in some implementations).

@go-english
Copy link

@jub0bs HI,bro.thanks for your reply.
this is my code,assume it's expose url:https://www.myserver.com

var Router = gin.Default()
Router.Use(middleware.NewCors())         
func NewCors() gin.HandlerFunc 
	return cors.New(cors.Config{
		AllowOrigins:     []string{"https://www.myhome.com"},
		AllowMethods:     []string{"POST", "GET", "OPTIONS"},
		AllowHeaders:     []string{"Content-Type", "x-token"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
		MaxAge:           7 * time.Hour * 24,
		AllowAllOrigins: false,
	})
}
}

i have the issue,if i set origins:"https://www.myhome.com"
why other address can access it? (example on my personal PC,it definite not "https://www.myhome.com" ,i use curl https://www.myserver.com, It should return me a 403 forbidden but not instead of customizing response)
if any hint i appreciate!

@go-english
Copy link

@jub0bs HI,bro.thanks for your reply. this is my code,assume it's expose url:https://www.myserver.com

var Router = gin.Default()
Router.Use(middleware.NewCors())         
func NewCors() gin.HandlerFunc 
	return cors.New(cors.Config{
		AllowOrigins:     []string{"https://www.myhome.com"},
		AllowMethods:     []string{"POST", "GET", "OPTIONS"},
		AllowHeaders:     []string{"Content-Type", "x-token"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
		MaxAge:           7 * time.Hour * 24,
		AllowAllOrigins: false,
	})
}
}

i have the issue,if i set origins:"https://www.myhome.com" why other address can access it? (example on my personal PC,it definite not "https://www.myhome.com" ,i use curl https://www.myserver.com, It should return me a 403 forbidden but not instead of customizing response) if any hint i appreciate!

i think i find problem,in cors.config.go
line 68

func (cors *cors) applyCors(c *gin.Context) {
	origin := c.Request.Header.Get("Origin")
	if len(origin) == 0 {
		// request is not a CORS request
		return
	}
	host := c.Request.Host

	if origin == "http://"+host || origin == "https://"+host {
		// request is not a CORS request but have origin header.
		// for example, use fetch api
		return
	}

	if !cors.validateOrigin(origin) {
		c.AbortWithStatus(http.StatusForbidden)
		return
	}

	if c.Request.Method == "OPTIONS" {
		cors.handlePreflight(c)
		defer c.AbortWithStatus(cors.optionsResponseStatusCode)
	} else {
		cors.handleNormal(c)
	}

	if !cors.allowAllOrigins {
		c.Header("Access-Control-Allow-Origin", origin)
	}
}`
allow all access,if don't set header origin.
i don't known,why?Shouldn't it be disabled by default?

@jub0bs
Copy link

jub0bs commented Apr 26, 2024

@go-english I'm not sure I understand the issue. Can you post one or more curl commands that trigger the behaviour you observe and also explain what behaviour you expect?

@go-english
Copy link

@jub0bs That i'm say,i set origin:https://www.myhome.com, expect only this url can access my server(https://www.myserver.com/), but i found i misunderstand .than i find this description in what is origin
I realize it can be null or fabricate,such as i use curl https://www.myserver.com(Not a server with [my server] deployed), and i was expecting it to not be able to access, but it can because it doesn't have an origin set.
Then i use curl -H "origin: https://www.myhome.com" https://www.myserver.com, it work too!,because i set fake origin
So it's not the code that's the problem, it's my misunderstand.
I guess I should have verified the ip of the visitor.That's what I need.
Thanks for you help

@jub0bs
Copy link

jub0bs commented Apr 26, 2024

@go-english I think you misunderstand the purpose of CORS. Contrary to popular belief, CORS is no substitute for server-side authorisation. Rather, CORS is a protocol that lets servers instruct browsers to relax the Same-Origin Policy's restrictions for select clients. All other things being equal, activating CORS makes your users less (not more) secure.

Besides, not all user agents implement the SOP or CORS. You shouldn't be surprised that you're able to spoof the Origin header using something like curl.

@go-english
Copy link

@jub0bs Yean,bro!I think i finally understand CORS can do something and not can do something.Thinks for you patience,have a nice day!

@mtarkar
Copy link

mtarkar commented Oct 2, 2024

config := cors.Config{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowWildcard:    false,
		MaxAge:           12 * time.Hour,
	}

This is my cors config. And even if i send a request from port 4200 or port 5000. Still the request is allowed by the server. So i agree with @go-english that it does not work properly. I have tried using curl and it works with curl but any requests sent from the web browser are allowed.

@jub0bs
Copy link

jub0bs commented Oct 2, 2024

@mtarkar You seem to be under the impression that configuring your server for CORS will block requests. This belief is incorrect; CORS is no defence. Please (re-)read my previous comment.

@mtarkar
Copy link

mtarkar commented Oct 28, 2024

@jub0bs Hey. I understood the problem. The problem was that i was trying to make the request from the server-side using a Next.js project. If we do it using a React Vite App or any other client-side framework it works from perfectly fine as it only blocks client-2-server communication. However, server-2-server communication is not blocked by CORs policies that was my observation after implementing CORs with a hybrid project like Next.js which can handle both client and server-side functionalities in the application. So the conclusion if anybody faces such a problem it is due to making CORs request from the server side. So there is no issue with the cors package, the problem happens only when it implemented from the server side. Thanks anyways 👍 It took some time for me to figure this out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants