gqlgen
gqlgen copied to clipboard
Broken CORS w/ WebSocket example
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
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."
+1
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:
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?
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.
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.