Skip to content

[Bug]: JWT middleware returns 500 for OPTIONS preflight requests #317

@pltchuong

Description

@pltchuong

Bug Description

The create_jwt_validation_middleware function does not skip HTTP OPTIONS requests. When a CDN, load balancer, or browser sends a CORS preflight (OPTIONS) to /api/messages, the middleware rejects it with a 401 (no Authorization header), which gets caught by the generic exception handler and returned as a 500.

Steps to Reproduce

Steps to reproduce:

curl -X OPTIONS https://<bot-endpoint>/api/messages

Expected Behavior

200 (preflight should be allowed without auth)

Actual Behavior

WARNING - Unauthorized request - missing or invalid authorization header
fastapi.exceptions.HTTPException: 401: unauthorized

Returned to the client as 500.

SDK Version

2.0.0a18

Python Version

3.12

Additional Context

Root cause: Line 38 checks the path but not the method:

# jwt_middleware.py:35-45
async def middleware(request: Request, call_next):
    if request.url.path not in paths:       # ← only checks path
        return await call_next(request)

    authorization = request.headers.get("authorization")
    if not authorization or not authorization.startswith("Bearer "):
        logger.warning("Unauthorized request - missing or invalid authorization header")
        raise HTTPException(status_code=401, detail="unauthorized")

Suggested fix: Add a method check:

if request.url.path not in paths or request.method == "OPTIONS":
    return await call_next(request)

Workaround: Register a middleware before the JWT middleware to short-circuit OPTIONS:

@app.http.app.middleware("http")
async def handle_options(request, call_next):
    if request.method == "OPTIONS":
        return Response(status_code=200)
    return await call_next(request)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions