FastAPI:如何仅为特定端点启用跨源资源共享(CORS)?

huangapple go评论91阅读模式
英文:

FastAPI: How to enable CORS only for specific endpoints?

问题

下面的示例将为应用程序中的所有端点启用CORS。如何仅针对特定端点或仅针对单个端点启用CORS,使用FastAPI?

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=False,
    allow_methods=["GET","DELETE"],
    allow_headers=["*"],
    max_age=0
)
英文:

The example below will enalbe CORS for all the endpoints in the application. How to enable CORS only for specific endpoints, or just an individual endpoint, using FastAPI?

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=False,
    allow_methods=["GET","DELETE"],
    allow_headers=["*"],
    max_age=0
)

答案1

得分: 3

你可以创建一个子应用程序,只包括你希望从与后端不同的来源访问的端点,并且仅在该子应用程序中添加CORSMiddleware

请注意,如此答案所述,在allow_origins参数中使用'*'通配符(如您的问题中所示),而不是像这里演示的指定特定来源,这意味着允许所有来源;但是,这会以排除涉及凭据(例如cookies授权头等)的一切为代价,因此将allow_credentials参数设置为True(请参阅Access-Control-Allow-Credentials响应头文档)将不会起作用,因此在执行跨来源请求时,仍无法在客户端和服务器之间发送/接收凭据(如上述所述)。更多详细信息,请参阅此处此处

工作示例

下面的示例中,可以访问位于http://127.0.0.1:8000/subapi/sub的subapi(子应用程序)中的/sub端点。

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

app = FastAPI()
subapi = FastAPI()

# 指定您希望后端(subapi)可以访问的来源
origins = ['http://localhost:3000']

subapi.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


@app.get('/app')
def read_main():
    return {'message': 'Hello World from main app;}


@subapi.get('/sub')
def read_sub():
    return {'message': 'Hello World from sub API;}


app.mount('/subapi', subapi)
英文:

You can create a Sub application with only the endpoints you wish to be accessible from a different origin than the backend, and add the CORSMiddleware to that sub app only.

Note that, as described in this answer, using the '*' wildcard in the allow_origins argument (as demonstrated in your question)—instead of specifying specific origins as demonstrated here—would mean that all origins are allowed; however, at the cost of excluding everything that involves credentials, such as cookies, authorization headers, etc; and hence, setting the allow_credentials argument to True (see Access-Control-Allow-Credentials response header documentation) would have no effect, and you still wouldn't be able to send/receive credentials (such as those described above) between the client and the server, when a cross-origin request is performed (see here and here for more details).

Working Example

The /sub endpoint from subapi (sub application) in the example below can be accessed at http://127.0.0.1:8000/subapi/sub

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

app = FastAPI()
subapi = FastAPI()

# specify the origins from which you wish the backend (subapi) to be accessible 
origins = ['http://localhost:3000']  

subapi.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


@app.get('/app')
def read_main():
    return {'message': 'Hello World from main app'}
    
 
@subapi.get('/sub')
def read_sub():
    return {'message': 'Hello World from sub API'}


app.mount('/subapi', subapi)

huangapple
  • 本文由 发表于 2023年1月8日 21:47:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定