FastAPI CORS 跨域
FastAPI CORS 跨域学习笔记一、什么是跨域问题1. 同源策略浏览器遵循同源策略Same-Origin Policy限制一个源的网页向另一个源发送请求。同源 协议 域名 端口 三者一致URL AURL B是否同源原因http://example.com/ahttp://example.com/b是协议/域名/端口相同http://example.comhttps://example.com否协议不同http://example.comhttp://api.example.com否域名不同http://example.comhttp://example.com:8080否端口不同2. 跨域错误表现前端http://localhost:3000请求后端http://localhost:8000时浏览器控制台报错Access to XMLHttpRequest at http://localhost:8000/api/data from origin http://localhost:3000 has been blocked by CORS policy: No Access-Control-Allow-Origin header is present on the requested resource.关键跨域限制是浏览器行为服务端之间互相调用不受影响。二、CORS 机制1. 简单请求满足以下所有条件的请求为简单请求浏览器直接发送在响应中检查 CORS 头方法为GET、HEAD、POST之一Content-Type 仅限于text/plain、multipart/form-data、application/x-www-form-urlencoded无自定义请求头浏览器 ──GET /api──→ 服务器 浏览器 ←── 响应 CORS头 ── 服务器 │ ├─ Access-Control-Allow-Origin 包含该源 → 放行 └─ 不包含 → 拦截2. 预检请求Preflight不满足简单请求条件的请求如含自定义头、PUT/DELETE方法、application/json浏览器会先发一个OPTIONS请求浏览器 ──OPTIONS /api──→ 服务器 ← 预检请求 浏览器 ←── 200 CORS头 ── 服务器 ← 预检响应 │ ├─ 预检通过 → 发送实际请求 └─ 预检失败 → 拦截不发送实际请求 浏览器 ──PUT /api──→ 服务器 ← 实际请求 浏览器 ←── 响应 CORS头 ── 服务器 ← 实际响应三、FastAPI 中配置 CORS1. 基本用法fromfastapiimportFastAPIfromfastapi.middleware.corsimportCORSMiddleware appFastAPI()app.add_middleware(CORSMiddleware,allow_origins[http://localhost:3000,https://example.com],allow_credentialsTrue,allow_methods[*],allow_headers[*],)2. 参数详解参数类型默认值说明allow_originslist[str][]允许的源列表[*]表示允许所有源allow_methodslist[str][GET]允许的 HTTP 方法[*]表示全部allow_headerslist[str][]允许的请求头[*]表示全部allow_credentialsboolFalse是否允许携带 Cookie / Authorizationexpose_headerslist[str][]允许前端访问的响应头max_ageintNone预检请求缓存时间秒3. 各参数对应的响应头参数对应的 CORS 响应头allow_originsAccess-Control-Allow-Originallow_methodsAccess-Control-Allow-Methodsallow_headersAccess-Control-Allow-Headersallow_credentialsAccess-Control-Allow-Credentialsexpose_headersAccess-Control-Expose-Headersmax_ageAccess-Control-Max-Age四、常见配置场景1. 开发环境 — 允许所有app.add_middleware(CORSMiddleware,allow_origins[*],allow_credentialsTrue,allow_methods[*],allow_headers[*],)注意allow_origins[*]与allow_credentialsTrue不能同时生效。浏览器规范要求携带凭证时Allow-Origin不能为*FastAPI 会自动忽略allow_credentials。2. 生产环境 — 精确控制app.add_middleware(CORSMiddleware,allow_origins[https://www.example.com,https://admin.example.com,],allow_credentialsTrue,allow_methods[GET,POST,PUT,DELETE],allow_headers[Authorization,Content-Type],expose_headers[X-Request-ID],max_age600,# 预检缓存 10 分钟)3. 动态来源 — 从环境变量读取importos originsos.getenv(CORS_ORIGINS,http://localhost:3000).split(,)app.add_middleware(CORSMiddleware,allow_origins[o.strip()foroinorigins],allow_credentialsTrue,allow_methods[*],allow_headers[*],)4. 支持子域名通配CORSMiddleware不支持*.example.com通配需自定义逻辑fromfastapiimportFastAPI,Requestfromfastapi.middleware.corsimportCORSMiddlewarefromstarlette.responsesimportResponse appFastAPI()ALLOWED_DOMAINS[example.com,example.org]defis_allowed_origin(origin:str)-bool:fromurllib.parseimporturlparse hostnameurlparse(origin).hostnameorreturnany(hostnamedorhostname.endswith(f.{d})fordinALLOWED_DOMAINS)app.middleware(http)asyncdefcors_middleware(request:Request,call_next):response:Responseawaitcall_next(request)originrequest.headers.get(origin)iforiginandis_allowed_origin(origin):response.headers[Access-Control-Allow-Origin]origin response.headers[Access-Control-Allow-Credentials]trueresponse.headers[Access-Control-Allow-Methods]GET, POST, PUT, DELETE, OPTIONSresponse.headers[Access-Control-Allow-Headers]Authorization, Content-Type# 处理预检请求ifrequest.methodOPTIONS:response.status_code200returnresponse五、CORS 中间件的工作流程请求到达 CORSMiddleware │ ├─ 是否为 OPTIONS 预检请求 │ ├─ 是 → 检查 Origin 是否在 allow_origins 中 │ │ ├─ 在 → 返回 200 CORS 头不转发到路由 │ │ └─ 不在 → 返回 400 │ │ │ └─ 否 → 继续处理 │ ├─ 检查 Origin 是否在 allow_origins 中 │ ├─ 在 → 转发到路由响应中添加 CORS 头 │ └─ 不在 → 转发到路由响应中不添加 CORS 头 │ └─ 浏览器根据响应中的 CORS 头决定是否放行六、allow_credentials的限制规则allow_originsallow_credentials行为[*]False允许所有源不携带凭证[*]True无效浏览器拒绝* credentials 组合具体源列表True正常工作允许指定源携带凭证凭证包含什么CookieHTTP 认证头AuthorizationTLS 客户端证书前端配合// axiosaxios.get(/api/data,{withCredentials:true});// fetchfetch(/api/data,{credentials:include});七、常见问题排查1. 仍然报跨域错误可能原因原因排查方式allow_origins未包含前端源检查浏览器控制台中的 Origin 值中间件注册顺序问题CORS 中间件应在其他中间件之前注册Nginx 重复添加 CORS 头检查 Nginx 配置移除重复的add_header预检请求被其他中间件拦截确认 OPTIONS 请求未被认证中间件拦截2. 响应头重复Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Origin: http://localhost:3000 ← 重复原因Nginx 和 FastAPI 都添加了 CORS 头。解决只在一处配置。3. Cookie 无法携带检查清单allow_credentialsTrueallow_origins不是[*]前端请求设置了withCredentials: trueCookie 的SameSite属性正确Cookie 的Secure属性与协议匹配HTTPS 需要Secure八、完整示例fromfastapiimportFastAPI,Cookie,Responsefromfastapi.middleware.corsimportCORSMiddleware appFastAPI()# ---- CORS 配置 ----app.add_middleware(CORSMiddleware,allow_origins[http://localhost:3000,https://www.example.com,],allow_credentialsTrue,allow_methods[GET,POST,PUT,DELETE,OPTIONS],allow_headers[Authorization,Content-Type,X-Request-ID],expose_headers[X-Request-ID],max_age600,)# ---- 路由 ----app.get(/api/data)asyncdefget_data():return{message:Hello from API}app.post(/api/login)asyncdeflogin(response:Response):response.set_cookie(keysession_id,valueabc123,httponlyTrue,samesitelax,)return{message:logged in}app.get(/api/profile)asyncdefprofile(session_id:strCookie(None)):ifnotsession_id:fromfastapiimportHTTPExceptionraiseHTTPException(status_code401,detailNot authenticated)return{session_id:session_id}九、注意事项生产环境禁止allow_origins[*]应明确列出允许的源防止恶意网站窃取用户数据。CORS 不是安全机制CORS 保护的是浏览器用户不保护服务器。服务端仍需做认证和鉴权。预检请求缓存设置max_age可减少 OPTIONS 请求次数降低延迟。中间件注册顺序add_middleware先注册的在外层CORS 应放在最外层最先注册。反向代理场景如果使用 Nginx建议在 Nginx 统一处理 CORS或确保只有一处添加 CORS 头。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2592935.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!