Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI CORS Cross-Origin

FastAPI CORS Cross-Origin

CORS (Cross-Origin Resource Sharing) is a security mechanism that allows or restricts web pages from requesting resources from different domains. In front-end/back-end separation development, front-end pages usually run on a different domain or port, so CORS must be configured to access the back-end API properly.


What is the Cross-Origin Problem

The browser's same-origin policy restricts web pages from sending requests to different domains. For example:

Front-end address Back-end API address Cross-origin?
http://localhost:3000 http://localhost:8000 Cross-origin (different port)
http://example.com http://api.example.com Cross-origin (different domain)
https://example.com http://example.com Cross-origin (different protocol)
http://example.com http://example.com/api Same origin (same domain, port, and protocol)

The three elements of same origin:Protocol、Domain names、port; if any differs, it is cross-origin.


Configure CORS

FastAPI uses Starlette's CORSMiddleware to handle cross-origin requests:

Example

from

fastapi

import

FastAPI

from

fastapi.

middleware

.

cors

import

CORSMiddleware

app

=

FastAPI

(

)

Configure CORS middleware

app.

add_middleware

(

    CORSMiddleware

,

    allow_origins

=

[

             

Allowed origins (list of domains)

       

"http://localhost:3000"

,

 

Front-end development server

       

"http://localhost:8080"

,

   

]

,

    allow_credentials

=

True

,

     

Allow credentials (cookies)

    allow_methods

=

[

"*"

]

,

         

Allowed HTTP methods

    allow_headers

=

[

"*"

]

,

         

Allowed request headers

)

@

app.

get

(

"/"

)

async

def

root

(

)

:

   

return

{

"message"

:

"Hello World"

}


CORS Configuration Parameters Explained

Parameters Type Description Recommended value
allow_origins list[str] List of allowed cross-origin sources Use specific domains in production
allow_methods list[str] Allowed HTTP methods ["GET", "POST", "PUT", "DELETE"]
allow_headers list[str] Allowed request headers Configure as needed
allow_credentials bool Whether to allow cookies and authentication credentials Set to true when authentication is needed True
expose_headers list[str] Response headers accessible to the front end Configure as needed
max_age int Cache time for preflight requests (seconds) 600

allow_origins Use ["*"] means allowing all origins, but this is incompatible with allow_credentials=True . If cookies need to be carried, specific origins must be specified.


Development vs Production

Development environment

For convenience during development, you can allow all origins:

Example

from

fastapi

import

FastAPI

from

fastapi.

middleware

.

cors

import

CORSMiddleware

app

=

FastAPI

(

)

Development: allow all origins (for development only!)

app.

add_middleware

(

    CORSMiddleware

,

    allow_origins

=

[

"*"

]

,

       

Allow all origins

    allow_credentials

=

True

,

    allow_methods

=

[

"*"

]

,

       

Allow all methods

    allow_headers

=

[

"*"

]

,

       

Allow all headers

)

Production environment

Production must specify specific origins:

Example

from

fastapi

import

FastAPI

from

fastapi.

middleware

.

cors

import

CORSMiddleware

app

=

FastAPI

(

)

Production: only allow specific domains

app.

add_middleware

(

    CORSMiddleware

,

    allow_origins

=

[

       

"https://example.com"

,

         

Production front-end domain

       

"https://www.example.com"

,

     

Domain with www

   

]

,

    allow_credentials

=

True

,

    allow_methods

=

[

"GET"

,

"POST"

,

"PUT"

,

"DELETE"

]

,

    allow_headers

=

[

"Authorization"

,

"Content-Type"

]

,

    max_age

=

600

,

                 

Preflight request cached for 10 minutes

)

Using in production allow_origins=["*"] is a security risk that may lead to cross-site request forgery (CSRF) attacks. Be sure to specify the specific front-end domain.


CORS Preflight Requests

Before sending certain cross-origin requests, the browser first sends a OPTIONS preflight request, asking the server whether the actual request is allowed. CORS middleware handles preflight requests automatically.

Conditions requiring a preflight:

After setting max_age , the browser caches the preflight result and will not resend the preflight request within the specified time, reducing network overhead.


Summary