99designs / gqlgen

go generate based graphql server library
https://gqlgen.com
MIT License
9.94k stars 1.17k forks source link

Broken CORS w/ WebSocket example #1328

Open genert opened 4 years ago

genert commented 4 years ago

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

ghost commented 4 years ago

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."

voodoo-dn commented 4 years ago

+1

chriskolenko commented 4 years ago

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:

dailytravel commented 3 years ago

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?

0xfirefist commented 3 years ago

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.

sgloutnikov commented 3 years ago

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.