
Api Security Hardening
- 355 installs
- 202 repo stars
- Updated August 4, 2026
- secondsky/claude-skills
api-security-hardening is a Claude Code skill that hardens REST APIs with authentication, rate limiting, input validation, and security headers for developers who need production-ready defense-in-depth before launch or d
About
api-security-hardening is a Claude Code skill from the secondsky/claude-skills marketplace that guides developers through layered REST API security hardening for production deployments. The skill applies authentication and authorization patterns including JWT and OAuth2 best practices, per-IP and per-client rate limiting with stricter limits on auth endpoints, express-validator input sanitization, and security headers such as CSP, HSTS, X-Frame-Options, and CORS whitelisting. It ships middleware stack examples using Express utilities like helmet and demonstrates route-level limits for sensitive endpoints alongside explicit never-do operational rules. Developers reach for api-security-hardening during security audits, before production launch, or when remediating injection attacks, XSS, parameter pollution, and abusive client traffic. The skill includes a compact checklist so teams enforce secure API practices without ad-hoc security research across services.
- api-security-hardening
Api Security Hardening by the numbers
- 355 all-time installs (skills.sh)
- +14 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #1,147 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/secondsky/claude-skills --skill api-security-hardeningAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 355 |
|---|---|
| repo stars | ★ 202 |
| Last updated | August 4, 2026 |
| Repository | secondsky/claude-skills ↗ |
How do you harden REST APIs for production security?
Use api-security-hardening for development tasks
Who is it for?
Backend developers shipping Express or Node REST APIs who need a prescriptive security audit and middleware patterns before production or after finding vulnerabilities.
Skip if: Teams building internal prototypes without auth, GraphQL-only stacks without REST routes, or projects that already completed a formal penetration test with signed-off controls.
When should I use this skill?
A developer asks to secure a REST API, fix CORS or injection issues, add rate limiting, or run a pre-launch API security audit.
What you get
Hardened API middleware stack, input validation rules, rate-limit configuration, security header set, and a production security checklist.
- Security middleware configuration
- Input validation schemas
- Production security checklist
Files
API Security Hardening
Protect REST APIs against common vulnerabilities with multiple security layers.
Security Middleware Stack (Express)
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
app.use(helmet());
app.use(mongoSanitize());
app.use(xss());
app.use('/api/', rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
}));
app.use('/api/auth/', rateLimit({
windowMs: 15 * 60 * 1000,
max: 5
}));Input Validation
const { body, validationResult } = require('express-validator');
app.post('/users',
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }).matches(/[A-Z]/).matches(/[0-9]/),
body('name').trim().escape().isLength({ max: 100 }),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process request
}
);Security Headers
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy', "default-src 'self'");
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
});Security Checklist
- [ ] HTTPS everywhere
- [ ] Authentication on all protected routes
- [ ] Input validation and sanitization
- [ ] Rate limiting enabled
- [ ] Security headers configured
- [ ] CORS restricted to allowed origins
- [ ] No stack traces in production errors
- [ ] Audit logging enabled
- [ ] Dependencies regularly updated
Additional Implementations
See references/python-nginx.md for:
- Python FastAPI security middleware
- Pydantic input validation with password rules
- Nginx SSL/TLS and security headers configuration
- HTTP Parameter Pollution prevention
Never Do
- Trust user input without validation
- Return detailed errors in production
- Store secrets in code
- Use GET for state-changing operations
- Disable security for convenience
Python FastAPI and Nginx Security
Python FastAPI Implementation
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
from slowapi.util import get_remote_address
app = FastAPI()
# Trusted Host Middleware
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["api.example.com", "localhost"]
)
# CORS Configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
# Rate Limiting
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = "default-src 'self'"
return response
@app.post("/users")
@limiter.limit("5/minute")
async def create_user(request: Request, user: UserCreate):
# Input validation handled by Pydantic model
passInput Validation with Pydantic
from pydantic import BaseModel, EmailStr, validator
import re
class UserCreate(BaseModel):
email: EmailStr
password: str
name: str
@validator('password')
def password_strength(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not re.search(r'[A-Z]', v):
raise ValueError('Password must contain uppercase letter')
if not re.search(r'[0-9]', v):
raise ValueError('Password must contain digit')
if not re.search(r'[!@#$%^&*]', v):
raise ValueError('Password must contain special character')
return v
@validator('name')
def name_length(cls, v):
if len(v) > 100:
raise ValueError('Name too long')
return v.strip()Nginx Security Configuration
server {
listen 443 ssl http2;
server_name api.example.com;
# SSL Configuration
ssl_certificate /etc/ssl/certs/api.crt;
ssl_certificate_key /etc/ssl/private/api.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
# Security Headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'" always;
# Request Size Limits
client_max_body_size 10m;
client_body_timeout 12;
client_header_timeout 12;
# Block Suspicious Methods
if ($request_method !~ ^(GET|POST|PUT|DELETE|PATCH|OPTIONS)$) {
return 405;
}
# Rate Limiting Zone
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req zone=api burst=20 nodelay;
location /api/ {
proxy_pass http://backend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Request-ID $request_id;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name api.example.com;
return 301 https://$server_name$request_uri;
}HTTP Parameter Pollution Prevention
from fastapi import Query
from typing import List
# Prevent HPP by explicitly handling list parameters
@app.get("/search")
async def search(
q: str = Query(..., max_length=100),
tags: List[str] = Query(default=[], max_length=10)
):
# Only first value used if duplicated
return {"query": q, "tags": tags[:5]} # Limit array sizeRelated skills
How it compares
Pick api-security-hardening when you need prescriptive REST middleware and header checklists for Express services rather than generic secure-coding advice without route-level patterns.
FAQ
What does api-security-hardening cover?
api-security-hardening covers REST API defense-in-depth: authentication and authorization patterns, rate limiting, express-validator input sanitization, and security headers including CSP, HSTS, and CORS whitelisting. It provides Express middleware examples and an operational che
When should developers use api-security-hardening?
Developers should use api-security-hardening before production launch, during security audits, or when remediating injection, XSS, CORS, or brute-force vulnerabilities. The skill targets Express-style REST services needing prescriptive middleware and header guidance.