Debian Codegraph @

docs/topics/authentication.rst

raw
1 Authentication
2 ==============
3
4 The WebSocket protocol is designed for creating web applications that require
5 bidirectional communication between browsers and servers.
6
7 In most practical use cases, WebSocket servers need to authenticate clients in
8 order to route communications appropriately and securely.
9
10 :rfc:`6455` remains elusive when it comes to authentication:
11
12 This protocol doesn't prescribe any particular way that servers can
13 authenticate clients during the WebSocket handshake. The WebSocket
14 server can use any client authentication mechanism available to a
15 generic HTTP server, such as cookies, HTTP authentication, or TLS
16 authentication.
17
18 None of these three mechanisms works well in practice. Using cookies is
19 cumbersome, HTTP authentication isn't supported by all mainstream browsers,
20 and TLS authentication in a browser is an esoteric user experience.
21
22 Fortunately, there are better alternatives! Let's discuss them.
23
24 System design
25 -------------
26
27 Consider a setup where the WebSocket server is separate from the HTTP server.
28
29 Most servers built with websockets adopt this design because they're a component
30 in a web application and websockets doesn't aim at supporting HTTP.
31
32 The following diagram illustrates the authentication flow.
33
34 .. image:: authentication.svg
35
36 Assuming the current user is authenticated with the HTTP server (1), the
37 application needs to obtain credentials from the HTTP server (2) in order to
38 send them to the WebSocket server (3), who can check them against the database
39 of user accounts (4).
40
41 Usernames and passwords aren't a good choice of credentials here, if only
42 because passwords aren't available in clear text in the database.
43
44 Tokens linked to user accounts are a better choice. These tokens must be
45 impossible to forge by an attacker. For additional security, they can be
46 short-lived or even single-use.
47
48 Sending credentials
49 -------------------
50
51 Assume the web application obtained authentication credentials, likely a
52 token, from the HTTP server. There's four options for passing them to the
53 WebSocket server.
54
55 1. **Sending credentials as the first message in the WebSocket connection.**
56
57 This is fully reliable and the most secure mechanism in this discussion. It
58 has two minor downsides:
59
60 * Authentication is performed at the application layer. Ideally, it would
61 be managed at the protocol layer.
62
63 * Authentication is performed after the WebSocket handshake, making it
64 impossible to monitor authentication failures with HTTP response codes.
65
66 2. **Adding credentials to the WebSocket URI in a query parameter.**
67
68 This is also fully reliable but less secure. Indeed, it has a major
69 downside:
70
71 * URIs end up in logs, which leaks credentials. Even if that risk could be
72 lowered with single-use tokens, it is usually considered unacceptable.
73
74 Authentication is still performed at the application layer but it can
75 happen before the WebSocket handshake, which improves separation of
76 concerns and enables responding to authentication failures with HTTP 401.
77
78 3. **Setting a cookie on the domain of the WebSocket URI.**
79
80 Cookies are undoubtedly the most common and hardened mechanism for sending
81 credentials from a web application to a server. In an HTTP application,
82 credentials would be a session identifier or a serialized, signed session.
83
84 Unfortunately, when the WebSocket server runs on a different domain from
85 the web application, this idea hits the wall of the `Same-Origin Policy`_.
86 For security reasons, setting a cookie on a different origin is impossible.
87
88 The proper workaround consists in:
89
90 * creating a hidden iframe_ served from the domain of the WebSocket server
91 * sending the token to the iframe with postMessage_
92 * setting the cookie in the iframe
93
94 before opening the WebSocket connection.
95
96 Sharing a parent domain (e.g. example.com) between the HTTP server (e.g.
97 www.example.com) and the WebSocket server (e.g. ws.example.com) and setting
98 the cookie on that parent domain would work too.
99
100 However, the cookie would be shared with all subdomains of the parent
101 domain. For a cookie containing credentials, this is unacceptable.
102
103 .. _Same-Origin Policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
104 .. _iframe: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
105 .. _postMessage: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
106
107 4. **Adding credentials to the WebSocket URI in user information.**
108
109 Letting the browser perform HTTP Basic Auth is a nice idea in theory.
110
111 In practice it doesn't work due to browser support limitations:
112
113 * Chrome behaves as expected.
114
115 * Firefox caches credentials too aggressively.
116
117 When connecting again to the same server with new credentials, it reuses
118 the old credentials, which may be expired, resulting in an HTTP 401. Then
119 the next connection succeeds. Perhaps errors clear the cache.
120
121 When tokens are short-lived or single-use, this bug produces an
122 interesting effect: every other WebSocket connection fails.
123
124 * Safari behaves as expected.
125
126 Two other options are off the table:
127
128 1. **Setting a custom HTTP header**
129
130 This would be the most elegant mechanism, solving all issues with the options
131 discussed above.
132
133 Unfortunately, it doesn't work because the `WebSocket API`_ doesn't support
134 `setting custom headers`_.
135
136 .. _WebSocket API: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
137 .. _setting custom headers: https://github.com/whatwg/html/issues/3062
138
139 2. **Authenticating with a TLS certificate**
140
141 While this is suggested by the RFC, installing a TLS certificate is too far
142 from the mainstream experience of browser users. This could make sense in
143 high security contexts.
144
145 I hope that developers working on projects in this category don't take
146 security advice from the documentation of random open source projects :-)
147
148 Let's experiment!
149 -----------------
150
151 The `experiments/authentication`_ directory demonstrates these techniques.
152
153 Run the experiment in an environment where websockets is installed:
154
155 .. _experiments/authentication: https://github.com/python-websockets/websockets/tree/main/experiments/authentication
156
157 .. code-block:: console
158
159 $ python experiments/authentication/app.py
160 Running on http://localhost:8000/
161
162 When you browse to the HTTP server at http://localhost:8000/ and you submit a
163 username, the server creates a token and returns a testing web page.
164
165 This page opens WebSocket connections to four WebSocket servers running on
166 four different origins. It attempts to authenticate with the token in four
167 different ways.
168
169 First message
170 .............
171
172 As soon as the connection is open, the client sends a message containing the
173 token:
174
175 .. code-block:: javascript
176
177 const websocket = new WebSocket("ws://.../");
178 websocket.onopen = () => websocket.send(token);
179
180 // ...
181
182 At the beginning of the connection handler, the server receives this message
183 and authenticates the user. If authentication fails, the server closes the
184 connection:
185
186 .. code-block:: python
187
188 from websockets.frames import CloseCode
189
190 async def first_message_handler(websocket):
191 token = await websocket.recv()
192 user = get_user(token)
193 if user is None:
194 await websocket.close(CloseCode.INTERNAL_ERROR, "authentication failed")
195 return
196
197 ...
198
199 Query parameter
200 ...............
201
202 The client adds the token to the WebSocket URI in a query parameter before
203 opening the connection:
204
205 .. code-block:: javascript
206
207 const uri = `ws://.../?token=${token}`;
208 const websocket = new WebSocket(uri);
209
210 // ...
211
212 The server intercepts the HTTP request, extracts the token and authenticates
213 the user. If authentication fails, it returns an HTTP 401:
214
215 .. code-block:: python
216
217 async def query_param_auth(connection, request):
218 token = get_query_param(request.path, "token")
219 if token is None:
220 return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Missing token\n")
221
222 user = get_user(token)
223 if user is None:
224 return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Invalid token\n")
225
226 connection.username = user
227
228 Cookie
229 ......
230
231 The client sets a cookie containing the token before opening the connection.
232
233 The cookie must be set by an iframe loaded from the same origin as the
234 WebSocket server. This requires passing the token to this iframe.
235
236 .. code-block:: javascript
237
238 // in main window
239 iframe.contentWindow.postMessage(token, "http://...");
240
241 // in iframe
242 document.cookie = `token=${data}; SameSite=Strict`;
243
244 // in main window
245 const websocket = new WebSocket("ws://.../");
246
247 // ...
248
249 This sequence must be synchronized between the main window and the iframe.
250 This involves several events. Look at the full implementation for details.
251
252 The server intercepts the HTTP request, extracts the token and authenticates
253 the user. If authentication fails, it returns an HTTP 401:
254
255 .. code-block:: python
256
257 async def cookie_auth(connection, request):
258 # Serve iframe on non-WebSocket requests
259 ...
260
261 token = get_cookie(request.headers.get("Cookie", ""), "token")
262 if token is None:
263 return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Missing token\n")
264
265 user = get_user(token)
266 if user is None:
267 return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Invalid token\n")
268
269 connection.username = user
270
271 User information
272 ................
273
274 The client adds the token to the WebSocket URI in user information before
275 opening the connection:
276
277 .. code-block:: javascript
278
279 const uri = `ws://token:${token}@.../`;
280 const websocket = new WebSocket(uri);
281
282 // ...
283
284 Since HTTP Basic Auth is designed to accept a username and a password rather
285 than a token, we send ``token`` as username and the token as password.
286
287 The server intercepts the HTTP request, extracts the token and authenticates
288 the user. If authentication fails, it returns an HTTP 401:
289
290 .. code-block:: python
291
292 from websockets.asyncio.server import basic_auth as websockets_basic_auth
293
294 def check_credentials(username, password):
295 return username == get_user(password)
296
297 basic_auth = websockets_basic_auth(check_credentials=check_credentials)
298
299 Machine-to-machine authentication
300 ---------------------------------
301
302 When the WebSocket client is a standalone program rather than a script running
303 in a browser, there are far fewer constraints. HTTP Authentication is the best
304 solution in this scenario.
305
306 To authenticate a websockets client with HTTP Basic Authentication
307 (:rfc:`7617`), include the credentials in the URI:
308
309 .. code-block:: python
310
311 from websockets.asyncio.client import connect
312
313 async with connect(f"wss://{username}:{password}@.../") as websocket:
314 ...
315
316 You must :func:`~urllib.parse.quote` ``username`` and ``password`` if they
317 contain unsafe characters.
318
319 To authenticate a websockets client with HTTP Bearer Authentication
320 (:rfc:`6750`), add a suitable ``Authorization`` header:
321
322 .. code-block:: python
323
324 from websockets.asyncio.client import connect
325
326 headers = {"Authorization": f"Bearer {token}"}
327 async with connect("wss://.../", additional_headers=headers) as websocket:
328 ...