Security on Websocket #170
-
Hello I am trying to get this working: https://fastapi.tiangolo.com/advanced/websockets/#using-depends-and-others Here is my basic example that fails:
Regular REST API endpoint works with HTTPAuthorizationCredentials ... it takes the "Authorization Bearer XXX" header, but not when using websocket endpoint ... What am i misunderstanding? I dont see any errors in my logs though, not sure why... i just get "Error: Unexpected server response: 500" Works for regular REST API endpoints though:
I also tried Depends() instead of Security() but it's the same result. Many thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Hmm i thought HTTPBearer is problematic, but this doesn't work either ...
This should work via query param, right, like so:
Isn't this the same as in docs? i'm confused now ... |
Beta Was this translation helpful? Give feedback.
-
To be honest, I am not very experienced with WebSockets, your example looks almost the same as the one in FastAPI docs. When you say "it doesn't work", what exactly happens? Could you try running it either in a debugger or adding some logging to make sure that your dependency |
Beta Was this translation helpful? Give feedback.
-
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:
Which can then be parsed on the backend side and validate the token. Fastapi code:
|
Beta Was this translation helpful? Give feedback.
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: