Skip to content

Commit a4b774d

Browse files
[Docs] subscription authentication (#385)
This PR improves the documentation about authentication with Subscription client. Co-authored-by: Ben Kraft <[email protected]>
1 parent 6309a6e commit a4b774d

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

docs/subscriptions.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ func (md *MyDialer) DialContext(ctx context.Context, urlStr string, requestHeade
6060
}
6161
config.Dialer = md.dialer
6262
config.Protocol = append(config.Protocol, "graphql-transport-ws")
63+
for key, values := range requestHeader {
64+
for _, value := range values {
65+
config.Header.Add(key, value)
66+
}
67+
}
6368

6469
// Connect to the WebSocket server
6570
conn, err := websocket.DialConfig(config)
@@ -110,13 +115,45 @@ a loop for incoming messages and errors:
110115
case err = <-errChan:
111116
return
112117
case <-time.After(time.Minute):
113-
err = wsClient.Unsubscribe(subscriptionID)
118+
err = graphqlClient.Unsubscribe(subscriptionID)
114119
loop = false
115120
}
116121
}
117122
```
118123

119124
To change the websocket protocol from its default value `graphql-transport-ws`, add the following header before calling `graphql.NewClientUsingWebSocket()`:
125+
120126
```go
121127
headers.Add("Sec-WebSocket-Protocol", "graphql-ws")
122128
```
129+
130+
## Authenticate subscriptions
131+
132+
Graphql allows to authenticate subscriptions using HTTP headers (inside the http upgrade request) or using connection parameters (first message inside the websocket connection).
133+
To authenticate using both methods, you need to add a `graphql.WebSocketOption` to the `graphql.NewClientUsingWebSocket` method.
134+
135+
### Example using HTTP headers
136+
137+
```go
138+
graphql.NewClientUsingWebSocket(
139+
endpoint,
140+
&MyDialer{Dialer: dialer},
141+
graphql.WithConnectionParams(map[string]interface{}{
142+
"headers": map[string]string{
143+
"Authorization": "Bearer " + token.AccessToken,
144+
},
145+
}),
146+
)
147+
```
148+
149+
### Example using connection parameters
150+
151+
```go
152+
graphql.NewClientUsingWebSocket(
153+
endpoint,
154+
&MyDialer{Dialer: dialer},
155+
graphql.WithWebsocketHeader(http.Header{
156+
"Authorization": []string{"Bearer " + token.AccessToken,},
157+
}),
158+
)
159+
```

0 commit comments

Comments
 (0)