Skip to content

Starlette CORSMiddleware works on localhost origin but not on frontend after deployed with Docker #3542

@kozzza

Description

@kozzza

Issue

My application uses a JWT cookie to authenticate requests. Wherever the @validate_jwt decorator is used, is a protected endpoint that needs that JWT in order to pass. Everything works as expected when I run this application locally through my terminal. However, once my application is deployed to Kubernetes through Docker, every endpoint I go to gives me a 502 response including the home path '/'. I am not sure what to do-- I've tried every instance of the origins list and this is the error I get on my frontend:

Access to XMLHttpRequest at 'https://my.frontend.com/api/authorize' from origin 'https://my.frontend.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here's my main file where my FastAPI instance is instantiated:

app.py

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    'http://localhost:3000',
    'https://localhost:3000',  
    'http://my.frontend.com',
    'https://my.frontend.com',
    'http://my.frontend.com:8000',
    'https://my.frontend.com:8000'
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
    expose_headers=['Set-Cookie']
)

@app.get('/')
def index():
    return {'status_code': 200, 'message': 'Home', 'data': {}}

@app.get('/api/authorize')
@validate_jwt
def authorize(request: Request, AUTH_JWT: str = Cookie(None)):    
    return {'status_code': 200, 'message': 'Success', 'data': {'authorized': True}}

# ...

if __name__ == "__main__":
    uvicorn.run("app:app", host="127.0.0.1", port=8000, reload=True, log_level="debug")

Environment

  • Python 3.8
  • FastAPI Version 0.66.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions