pyropy / fastapi-socketio

Easily integrate socket.io with your FastAPI app πŸš€
Apache License 2.0
328 stars 31 forks source link

[USAGE-NOTE] CORS configuration: multiple `access-control-allow-origin` header entries returned to client; chrome fails to upgrade connection. #13

Open inactivist opened 3 years ago

inactivist commented 3 years ago

(This may be a documentation issue -- in any case, this may be helpful to someone else)

EDIT I see this problem is mentioned in issue #2, but I didn't make the connection until after creating this issue.


I encountered a problem where Chrome refused to upgrade the connection, due to multiple CORS header being returned in the server response, when using fastapi.CORSMiddleware and setting allowed origins in both places

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    # allow any origin for development purposes, don't do this in production
    allow_origins=['*'], 
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
sio = SocketManager(app=app, cors_allowed_origins=['*'])

Seem obvious now, but setting both allow_origins in CORSMiddleware, and cors_allowed_origins in fastapi-socketio causes duplicate headers to be returned to the client (which causes errors in Chrome, and the connection isn't upgraded)

Related to python-socketio issue 205 -- this response recommends async_mode='sanic' and cors_allowed_origins=[] in the constructor:

    engineio.AsyncServer(async_mode='sanic', cors_allowed_origins=[])

I've confirmed that passing cors_allowed_origins=[] in the SocketManager() constructor resolves the issue in this situation.

(See also this issue)

pyropy commented 3 years ago

@inactivist Hey thank you for reporting this information. I'll test it out with sanic mode and update the docs accordingly! Thank you once again πŸš€πŸŽ‰

pyropy commented 3 years ago

@inactivist I'll add transport mode option to SocketManager constructor