ln-773-cors-configurator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ln-773-cors-configurator

ln-773-cors-configurator

Type: L3 Worker Category: 7XX Project Bootstrap Parent: ln-770-crosscutting-setup
Configures Cross-Origin Resource Sharing (CORS) policy with security-first approach.

类型: L3 Worker 分类: 7XX 项目初始化 父级: ln-770-crosscutting-setup
采用安全优先的方法配置跨源资源共享(CORS)策略。

Overview

概述

AspectDetails
InputContext Store from ln-770
OutputCORS configuration with environment-specific policies
Stacks.NET (ASP.NET Core CORS), Python (FastAPI CORSMiddleware)

方面详情
输入来自ln-770的上下文存储
输出带有环境特定策略的CORS配置
技术栈.NET (ASP.NET Core CORS), Python (FastAPI CORSMiddleware)

Phase 1: Receive Context

阶段1:接收上下文

Accept Context Store from coordinator.
Required Context:
  • STACK
    : .NET or Python
  • PROJECT_ROOT
    : Project directory path
  • ENVIRONMENT
    : Development or Production
Idempotency Check:
  • .NET: Grep for
    AddCors
    or
    UseCors
  • Python: Grep for
    CORSMiddleware
  • If found: Return
    { "status": "skipped" }

接收来自协调器的上下文存储。
必填上下文:
  • STACK
    : .NET 或 Python
  • PROJECT_ROOT
    : 项目目录路径
  • ENVIRONMENT
    : 开发或生产环境
幂等性检查:
  • .NET: 搜索
    AddCors
    UseCors
  • Python: 搜索
    CORSMiddleware
  • 如果找到: 返回
    { "status": "skipped" }

Phase 2: Analyze Project Structure

阶段2:分析项目结构

Determine frontend configuration.
Detection Steps:
  1. Check for frontend in same repository (
    /frontend
    ,
    /client
    ,
    /web
    )
  2. Read
    .env
    or
    appsettings.json
    for CORS_ORIGINS
  3. Identify common frontend ports (3000, 5173, 4200)
Detected Frontend Origins:
FrameworkDefault PortOrigin
React (CRA)3000http://localhost:3000
Vite5173http://localhost:5173
Angular4200http://localhost:4200
Next.js3000http://localhost:3000

确定前端配置。
检测步骤:
  1. 检查同一仓库中是否存在前端(
    /frontend
    ,
    /client
    ,
    /web
  2. 读取
    .env
    appsettings.json
    获取 CORS_ORIGINS
  3. 识别常见前端端口(3000, 5173, 4200)
检测到的前端源:
框架默认端口
React (CRA)3000http://localhost:3000
Vite5173http://localhost:5173
Angular4200http://localhost:4200
Next.js3000http://localhost:3000

Phase 3: Decision Points

阶段3:决策点

Q1: Allowed Origins

问题1:允许的源

EnvironmentStrategy
DevelopmentAllow localhost origins (configurable)
ProductionExplicit origins from environment variables only
Security Warning: Never use
*
(wildcard) with credentials.
环境策略
开发环境允许localhost源(可配置)
生产环境仅允许环境变量中明确指定的源
安全警告: 永远不要在带凭证的请求中使用
*
(通配符)。

Q2: Allowed Methods

问题2:允许的方法

MethodDefaultNotes
GET✓ YesRead operations
POST✓ YesCreate operations
PUT✓ YesUpdate operations
DELETE✓ YesDelete operations
PATCHOptionalPartial updates
OPTIONS✓ YesPreflight requests (automatic)
方法默认设置说明
GET✓ 是读取操作
POST✓ 是创建操作
PUT✓ 是更新操作
DELETE✓ 是删除操作
PATCH可选部分更新
OPTIONS✓ 是预检请求(自动处理)

Q3: Credentials Support

问题3:凭证支持

ScenarioAllowCredentialsNotes
Cookie-based auth✓ YesRequired for cookies
JWT in header✗ NoNot needed
OAuth2DependsCheck documentation
Warning: AllowCredentials = true prohibits
*
origin.
场景是否允许凭证说明
基于Cookie的认证✓ 是Cookie必需
JWT在请求头中✗ 否不需要
OAuth2视情况而定查看文档
警告: 当AllowCredentials = true时,禁止使用
*
作为源。

Q4: Preflight Cache Duration

问题4:预检缓存时长

EnvironmentMaxAgeRationale
Development0Immediate config changes
Production86400 (24h)Reduce preflight requests

环境最大时长理由
开发环境0立即应用配置变更
生产环境86400(24小时)减少预检请求

Phase 4: Generate Configuration

阶段4:生成配置

.NET Output Files

.NET输出文件

FilePurpose
Extensions/CorsExtensions.cs
CORS service registration
appsettings.json
(update)
Origins configuration
appsettings.Development.json
(update)
Dev origins
Generation Process:
  1. Use MCP ref for current ASP.NET Core CORS API
  2. Generate CorsExtensions with:
    • Development policy (permissive)
    • Production policy (restrictive)
    • Environment-based policy selection
  3. Update appsettings with CORS:Origins
Registration Code:
csharp
builder.Services.AddCorsPolicy(builder.Configuration);
// ...
app.UseCors(builder.Environment.IsDevelopment() ? "Development" : "Production");
文件用途
Extensions/CorsExtensions.cs
CORS服务注册
appsettings.json
(更新)
源配置
appsettings.Development.json
(更新)
开发环境源
生成流程:
  1. 使用MCP参考当前ASP.NET Core CORS API
  2. 生成CorsExtensions,包含:
    • 开发环境策略(宽松)
    • 生产环境策略(严格)
    • 基于环境的策略选择
  3. 更新appsettings中的CORS:Origins
注册代码:
csharp
builder.Services.AddCorsPolicy(builder.Configuration);
// ...
app.UseCors(builder.Environment.IsDevelopment() ? "Development" : "Production");

Python Output Files

Python输出文件

FilePurpose
middleware/cors_config.py
CORS middleware configuration
.env
(update)
CORS_ORIGINS variable
Generation Process:
  1. Use MCP ref for FastAPI CORSMiddleware
  2. Generate cors_config.py with:
    • Origin parsing from environment
    • Method and header configuration
    • Credentials handling
  3. Update .env with CORS_ORIGINS
Registration Code:
python
from middleware.cors_config import configure_cors
configure_cors(app)

文件用途
middleware/cors_config.py
CORS中间件配置
.env
(更新)
CORS_ORIGINS变量
生成流程:
  1. 使用MCP参考FastAPI CORSMiddleware
  2. 生成cors_config.py,包含:
    • 从环境变量解析源
    • 方法和请求头配置
    • 凭证处理
  3. 更新.env中的CORS_ORIGINS
注册代码:
python
from middleware.cors_config import configure_cors
configure_cors(app)

Phase 5: Validate

阶段5:验证

Validation Steps:
  1. Syntax check:
    • .NET:
      dotnet build --no-restore
    • Python:
      python -m py_compile middleware/cors_config.py
  2. CORS test:
    bash
    # Test preflight request
    curl -X OPTIONS http://localhost:5000/api/test \
      -H "Origin: http://localhost:3000" \
      -H "Access-Control-Request-Method: POST" \
      -v
  3. Verify headers:
    • Access-Control-Allow-Origin
      : Should match request origin
    • Access-Control-Allow-Methods
      : Should list allowed methods
    • Access-Control-Allow-Credentials
      : true (if enabled)
    • Access-Control-Max-Age
      : Cache duration

验证步骤:
  1. 语法检查:
    • .NET:
      dotnet build --no-restore
    • Python:
      python -m py_compile middleware/cors_config.py
  2. CORS测试:
    bash
    # 测试预检请求
    curl -X OPTIONS http://localhost:5000/api/test \
      -H "Origin: http://localhost:3000" \
      -H "Access-Control-Request-Method: POST" \
      -v
  3. 验证响应头:
    • Access-Control-Allow-Origin
      : 应与请求源匹配
    • Access-Control-Allow-Methods
      : 应列出允许的方法
    • Access-Control-Allow-Credentials
      : true(如果启用)
    • Access-Control-Max-Age
      : 缓存时长

Security Checklist

安全检查清单

Before completing, verify:
  • No wildcard
    *
    origin in production
  • Explicit allowed methods (not
    AllowAnyMethod
    in prod)
  • Credentials only if needed
  • Origins from environment variables in production
  • Preflight caching enabled in production

完成前,请验证:
  • 生产环境中不使用通配符
    *
    作为源
  • 明确指定允许的方法(生产环境中不使用
    AllowAnyMethod
  • 仅在需要时启用凭证支持
  • 生产环境中从环境变量获取源
  • 生产环境中启用预检缓存

Return to Coordinator

返回协调器

json
{
  "status": "success",
  "files_created": [
    "Extensions/CorsExtensions.cs"
  ],
  "packages_added": [],
  "registration_code": "builder.Services.AddCorsPolicy(configuration);",
  "message": "Configured CORS with Development and Production policies"
}

json
{
  "status": "success",
  "files_created": [
    "Extensions/CorsExtensions.cs"
  ],
  "packages_added": [],
  "registration_code": "builder.Services.AddCorsPolicy(configuration);",
  "message": "Configured CORS with Development and Production policies"
}

Reference Links

参考链接


Version: 2.0.0 Last Updated: 2026-01-10

版本: 2.0.0 最后更新: 2026-01-10