home / skills / levnikolaevich / claude-code-skills / ln-773-cors-configurator

ln-773-cors-configurator skill

/ln-773-cors-configurator

This skill configures environment-specific CORS policies for development and production, ensuring secure origins, methods, and credentials across .NET and

npx playbooks add skill levnikolaevich/claude-code-skills --skill ln-773-cors-configurator

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
6.2 KB
---
name: ln-773-cors-configurator
description: Configures CORS policy for development and production
---

# 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.

---

## Overview

| Aspect | Details |
|--------|---------|
| **Input** | Context Store from ln-770 |
| **Output** | CORS configuration with environment-specific policies |
| **Stacks** | .NET (ASP.NET Core CORS), Python (FastAPI CORSMiddleware) |

---

## Phase 1: Receive Context

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" }`

---

## Phase 2: Analyze Project Structure

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:**

| Framework | Default Port | Origin |
|-----------|--------------|--------|
| React (CRA) | 3000 | http://localhost:3000 |
| Vite | 5173 | http://localhost:5173 |
| Angular | 4200 | http://localhost:4200 |
| Next.js | 3000 | http://localhost:3000 |

---

## Phase 3: Decision Points

### Q1: Allowed Origins

| Environment | Strategy |
|-------------|----------|
| **Development** | Allow localhost origins (configurable) |
| **Production** | Explicit origins from environment variables only |

**Security Warning:** Never use `*` (wildcard) with credentials.

### Q2: Allowed Methods

| Method | Default | Notes |
|--------|---------|-------|
| GET | ✓ Yes | Read operations |
| POST | ✓ Yes | Create operations |
| PUT | ✓ Yes | Update operations |
| DELETE | ✓ Yes | Delete operations |
| PATCH | Optional | Partial updates |
| OPTIONS | ✓ Yes | Preflight requests (automatic) |

### Q3: Credentials Support

| Scenario | AllowCredentials | Notes |
|----------|------------------|-------|
| Cookie-based auth | ✓ Yes | Required for cookies |
| JWT in header | ✗ No | Not needed |
| OAuth2 | Depends | Check documentation |

**Warning:** AllowCredentials = true prohibits `*` origin.

### Q4: Preflight Cache Duration

| Environment | MaxAge | Rationale |
|-------------|--------|-----------|
| Development | 0 | Immediate config changes |
| Production | 86400 (24h) | Reduce preflight requests |

---

## Phase 4: Generate Configuration

### .NET Output Files

| File | Purpose |
|------|---------|
| `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");
```

### Python Output Files

| File | Purpose |
|------|---------|
| `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)
```

---

## Phase 5: Validate

**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

---

## 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

---

## 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"
}
```

---

## Reference Links

- [ASP.NET Core CORS](https://learn.microsoft.com/aspnet/core/security/cors)
- [FastAPI CORS](https://fastapi.tiangolo.com/tutorial/cors/)
- [MDN CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS)

---

## Critical Rules

- **Never use wildcard `*` origin with credentials** — security violation per CORS spec
- **Production origins from environment variables only** — no hardcoded URLs in code
- **Separate Development and Production policies** — permissive locally, restrictive in production
- **Idempotent** — if `AddCors`/`UseCors` or `CORSMiddleware` exists, return `status: "skipped"`
- **Enable preflight caching in Production** — MaxAge 86400 (24h) to reduce OPTIONS requests

## Definition of Done

- Context Store received (stack, project root, environment)
- Frontend origins detected (port/framework auto-detection)
- User decisions collected (origins, methods, credentials, cache duration)
- CORS configuration generated with environment-specific policies
- Security checklist verified (no wildcard + credentials, explicit methods, env-based origins)
- Syntax validated (`dotnet build` or `py_compile`)
- Structured JSON response returned to ln-770 coordinator

---

**Version:** 2.0.0
**Last Updated:** 2026-01-10

Overview

This skill configures Cross-Origin Resource Sharing (CORS) policies for development and production with a security-first approach. It supports .NET (ASP.NET Core) and Python (FastAPI) stacks, generating environment-specific registrations and configuration files. The skill is idempotent and returns early if CORS is already configured.

How this skill works

The skill accepts a Context Store containing STACK, PROJECT_ROOT, and ENVIRONMENT. It scans the repository for existing CORS setup, detects a frontend origin from common folders or config files, and proposes environment-aware policies. Finally it generates or updates files (CorsExtensions.cs, middleware/cors_config.py, .env or appsettings) and validates syntax and runtime behavior with simple preflight tests.

When to use it

  • Bootstrapping a new backend project that needs browser access from a frontend during development.
  • Adding secure CORS controls to an existing .NET or FastAPI service where origins must be environment-specific.
  • Preparing production deployments that must avoid wildcard origins and enforce explicit allowed origins.
  • Automating policy generation when a coordinator provides repository and environment context.
  • Ensuring idempotent CORS configuration as part of cross-cutting setup workflows.

Best practices

  • Allow localhost origins only in development; use explicit origins from environment variables in production.
  • Never use '*' origin when credentials are enabled; require explicit origin matching in production.
  • Limit allowed methods to the minimum required for the API; avoid AllowAnyMethod in production.
  • Enable Access-Control-Max-Age for production (24h) to reduce preflight traffic; keep it 0 in development.
  • Store production origins in environment variables or appsettings, never hardcode production URLs.

Example use cases

  • Generate CorsExtensions.cs and update appsettings.json for an ASP.NET Core API based on detected frontend ports.
  • Create middleware/cors_config.py and add CORS_ORIGINS to .env for a FastAPI service that serves a Vite frontend.
  • Run idempotency check in a CI step to skip configuration if AddCors or CORSMiddleware already exists.
  • Validate CORS behavior with a scripted curl OPTIONS preflight check during deployment verification.

FAQ

What happens if CORS is already configured?

The skill performs an idempotency check and returns status 'skipped' if AddCors/UseCors or CORSMiddleware is detected.

Can I allow credentials and use wildcard origins?

No. Allowing credentials with '*' is a security violation; production must use explicit origins when credentials are enabled.