Skip to content

Commit

Permalink
Fix #80: Document caveats, related to authentication in Websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
dolamroth committed Mar 7, 2024
1 parent 5aed29b commit de6d589
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/common/websockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ Receipts:
- for an example of simple chat, see `starlette_web.tests.views.websocket.ChatWebsocketTestEndpoint` and
`starlette_web.tests.contrib.test_websocket_chat`

### Authentication

While generic WebSocket protocol does allow using headers, browsers' WebSocket API does not allow user
to set request headers, such as "Authorization".

Instead, use advice from StackOverflow answer:
https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api/77060459#77060459

**TL;DR**: pass authentication credentials as custom protocol, which is internally changed to
"Sec-WebSocket-Protocol" header. This feature is supported by majority or modern browsers.

## Synchronizing multiple tasks

It is not recommended to run a highly-sophisticated logic with many infinite tasks,
Expand Down
3 changes: 3 additions & 0 deletions starlette_web/tests/views/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ async def _handle_background_task_exception(


class AuthenticationWebsocketTestEndpoint(BaseWebsocketTestEndpoint):
# Note, that authentication via "Authorization" header
# is not supported by web-browsers' WebSocket API.
# Instead, use custom schema, such as setting "Sec-WebSocket-Protocol" header.
auth_backend = JWTAuthenticationBackend
permission_classes = [IsAuthenticatedPermission]
EXIT_MAX_DELAY = 5
Expand Down

0 comments on commit de6d589

Please sign in to comment.