dorinclisu / fastapi-auth0

FastAPI authentication and authorization using auth0.com
MIT License
230 stars 39 forks source link

Websocket Auth Support #24

Closed josecsotomorales closed 1 year ago

josecsotomorales commented 2 years ago

The auth flow currently uses Auth0HTTPBearer, which depends on a Request instance (http), for Websockets, I think we need to use cookies to pass the token?

dorinclisu commented 2 years ago

I don't think cookies would work. The problem is that Websockets lacks standardisation when it comes to authentication, so you could do it in many many ways according to the security requirements of the app and the frontend constraints.

If you want to use auth0 access tokens, you first have to agree between frontend and backend on a mechanism to pass the token to the websocket server, this could be done as a request header or as the first connect message for example. Then, the most straighforward way (but not necessarily the best) in the backend is to do user = auth.get_user(SecurityScopes(...), creds= HTTPAuthorizationCredentials(...)), while making sure your auth has auto_error=False and the user is checked before allowing or breaking the connection. I don't think the fastapi hierarchical dependency injection would work for websockets.

This messiness of websockets is why, if you do not need bidirectional connection and only want to push data from backend to frontend (like notifications), server sent events are easier and safer because the auth is already solved on http endpoints. Here is a SSE library for fastapi: https://github.com/sysid/sse-starlette

josecsotomorales commented 2 years ago

Thanks for the quick response @dorinclisu, in this case, I need bidirectional communication, cannot run away from WebSockets unfortunately, will try your suggestion and will share the codebase here.