You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The WebSocket protocol doesn’t handle authorization or authentication. Practically, this means that a WebSocket opened from a page behind auth doesn’t "automatically" receive any sort of auth. You need to take steps to also secure the WebSocket connection.
2
+
3
+
Since you cannot customize WebSocket headers from JavaScript, you’re limited to the "implicit" auth (i.e. Basic or cookies) that’s sent from the browser. The more common approach to generates a token from your normal HTTP server and then have the client send the token (either as a query string in the WebSocket path or as the first WebSocket message). The WebSocket server then validates that the token is valid.
4
+
5
+
**Note**: *Change all IP address to your localhost*
6
+
7
+
Here is an example of how you authorize from query URL:
8
+
```python hl_lines="42-52 65-66 71 73"
9
+
{!../examples/websocket.py!}
10
+
```
11
+
You will see a simple page like this:
12
+
13
+
<figure>
14
+
<imgsrc="https://bit.ly/3k2BpaM"/>
15
+
</figure>
16
+
17
+
You can copy the token from endpoint **/login** and then send them:
18
+
19
+
<figure>
20
+
<imgsrc="https://bit.ly/3k4Y9XC"/>
21
+
</figure>
22
+
23
+
And your WebSocket route will respond back if the token is valid or not:
24
+
25
+
<figure>
26
+
<imgsrc="https://bit.ly/36ajZ7d"/>
27
+
</figure>
28
+
29
+
30
+
Here is an example of how you authorize from cookie:
31
+
```python hl_lines="30-47 60-61 66 68"
32
+
{!../examples/websocket_cookie.py!}
33
+
```
34
+
35
+
You will see a simple page like this:
36
+
37
+
<figure>
38
+
<imgsrc="https://bit.ly/2TXs8Gi"/>
39
+
</figure>
40
+
41
+
You can get the token from URL **/get-cookie**:
42
+
43
+
<figure>
44
+
<imgsrc="https://bit.ly/2I9qtLG"/>
45
+
</figure>
46
+
47
+
And click button send then your WebSocket route will respond back if the
48
+
cookie and csrf token is match or cookie is valid or not:
0 commit comments