gqlgen icon indicating copy to clipboard operation
gqlgen copied to clipboard

Broken CORS w/ WebSocket example

Open genert opened this issue 4 years ago • 6 comments

What happened?

When connecting via Apollo WebSocket link, it fails to connect due following error: Error during WebSocket handshake: Unexpected response code: 403

Checking server logs, following error is spotted:

[cors] 2020/09/14 12:44:17   Actual response added headers: map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[http://localhost:8080] Vary:[Origin]]
2020/09/14 12:44:17 unable to upgrade *http.response to websocket websocket: request origin not allowed by Upgrader.CheckOrigin:
2020/09/14 12:44:17 http: superfluous response.WriteHeader call from github.com/99designs/gqlgen/graphql/handler/transport.SendError (error.go:15)

What did you expect?

That it works...

Minimal graphql.schema and models to reproduce

https://gqlgen.com/recipes/cors/

versions

  • latest gqlgen version?
  • 1.15?
  • go modules

genert avatar Sep 14 '20 12:09 genert

Same issue here, testing my subscription in graphql-playground gets me the error: "error": "Could not connect to websocket endpoint ws://localhost:8080/query. Please check if the endpoint url is correct."

ghost avatar Sep 17 '20 08:09 ghost

+1

voodoo-dn avatar Sep 22 '20 12:09 voodoo-dn

If you're using the following to setup your graphql

	srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: resolvers}))

It adds the Websocket transport which uses a default Upgrader. The default upgrader uses SameOrigin. So if you're running your client on a different port it won't upgrade.

Giving you: unable to upgrade *http.response to websocket websocket: request origin not allowed by Upgrader.CheckOrigin:

chriskolenko avatar Oct 10 '20 09:10 chriskolenko

If you're using the following to setup your graphql

	srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: resolvers}))

It adds the Websocket transport which uses a default Upgrader. The default upgrader uses SameOrigin. So if you're running your client on a different port it won't upgrade.

Giving you: unable to upgrade *http.response to websocket websocket: request origin not allowed by Upgrader.CheckOrigin:

And how to fix it bro?

dailytravel avatar Nov 25 '20 12:11 dailytravel

I was facing the same issue. I found this https://outcrawl.com/go-graphql-realtime-chat. Instead of using the default graphql server we can create a new one in which we can specify cors policy.

0xfirefist avatar Dec 05 '20 13:12 0xfirefist

The quickest fix for me was to use handler.New() instead of handler.NewDefaultServer and add the transports myself.

You can see an example of that in the chat example. There is also another example in #1250.

sgloutnikov avatar Dec 10 '20 03:12 sgloutnikov