Skip to content

Security on Websocket #170

Answered by developer992
developer992 asked this question in Q&A
Discussion options

You must be logged in to vote

Hey, sorry, i solved this using sub-protocol header.

Websocket connection does not support headers, except a few specific ones, for instance "Sub-Protocol" which is often used to hack/hide the token with. Wanted to avoid query params as to not expose the token.

Basically, the header will look like this:

Sec-WebSocket-Protocol: token, eyabcblabla

Which can then be parsed on the backend side and validate the token.

Fastapi code:

WEBSOCKET_TOKEN_SUBPROTOCOL = "token"    # this is the name of the subprotocol and can be any string

async def login_required_ws(
    websocket: WebSocket,
) -> User:
    """ 
    Websocket endpoints do not support all headers, so we need to send the token in sub-p…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by tomasvotava
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants