Apply Secure Defaults
Configure frameworks and infrastructure with security enabled by default — HttpOnly/Secure/SameSite cookies, HTTPS enforcement, debug disabled, strong cipher suites, and framework security middleware — preventing entire vulnerability classes through configuration rather than per-feature implementation.
Why This Is Best Practice
Adopted by: OWASP Top 10 Proactive Controls C05 (Secure By Default Configurations) and C09 (Leverage Security Frameworks and Libraries). Django, Rails, Spring Security, and ASP.NET Core all ship with security defaults that must be explicitly disabled — enabling them is zero-effort compared to implementing the equivalent from scratch. OWASP ASVS 14.1 (Build and Deploy) defines the configuration security requirements. Google's BeyondProd and Netflix's "Paved Road" security model both use security-by-default infrastructure as the primary mechanism for consistent security posture across thousands of services.
Impact: The 2021 Log4Shell vulnerability (CVSS 10.0, estimated $6.2B remediation cost) was exploited partly because Java application servers had JNDI lookups enabled by default — disabled by default would have prevented exploitation on most targets without a single line of code change. Django's default DEBUG = False in production prevents stack traces from being served to users; teams that deploy with DEBUG = True expose full database queries, environment variables, and code to anyone who triggers an error. A CIS Benchmark analysis (2022) found that 65% of remediated cloud misconfigurations were default settings that were never reviewed.
Why best: Per-feature security implementation (add CSRF protection here, add XSS escaping there) creates gaps — developers forget or don't know every security requirement. Secure defaults mean a developer who knows nothing about security still gets CSRF protection, secure cookies, and HTTPS enforcement automatically. The alternative (security off by default, enabled per-feature) results in security that's only as good as the developer's security knowledge.
Sources: OWASP Proactive Controls C05, C09; OWASP ASVS 14.1; Django security documentation; Rails security guide; Netflix Paved Road security model
Steps
Django: verify all security middleware and settings are enabled:
# settings.py — production security checklist
# Run Django's built-in check: python manage.py check --deploy
# All items below must be verified
DEBUG = False # CRITICAL — never True in production
ALLOWED_HOSTS = ["app.company.com"] # explicit allowlist, not ["*"]
# HTTPS enforcement
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# Cookie security
SESSION_COOKIE_SECURE = True # only over HTTPS
SESSION_COOKIE_HTTPONLY = True # no JS access
SESSION_COOKIE_SAMESITE = "Lax" # CSRF protection
SESSION_COOKIE_AGE = 1800 # 30 min idle timeout
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = "Lax"
# Security middleware (order matters)
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware", # must be first
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
# ... other middleware
]
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = "DENY"
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
Express.js/Node.js: apply Helmet and secure defaults:
import express from 'express';
import helmet from 'helmet';
import session from 'express-session';
const app = express();
// Helmet sets 11 security headers in one call
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"], // no unsafe-inline
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
}));
// Session security
app.use(session({
secret: process.env.SESSION_SECRET, // from secrets manager
name: '__Host-session', // __Host- prefix requires Secure flag
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'lax',
maxAge: 30 * 60 * 1000, // 30 minutes
},
}));
// Disable Express fingerprinting
app.disable('x-powered-by');
// Never serve raw errors in production
app.use((err, req, res, next) => {
console.error(err); // log internally
res.status(500).json({ error: 'Internal server error' }); // generic externally
});
Spring Boot: security configuration baseline:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// HTTPS enforcement
.requiresChannel(channel -> channel.anyRequest().requiresSecure())
// HSTS
.headers(headers -> headers
.httpStrictTransportSecurity(hsts -> hsts
.maxAgeInSeconds(31536000)
.includeSubDomains(true)
.preload(true))
.contentTypeOptions(Customizer.withDefaults())
.frameOptions(frame -> frame.deny())
)
// Session management
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1)
.sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
)
// CSRF enabled by default — verify not disabled
.csrf(Customizer.withDefaults());
return http.build();
}
}
# application-production.properties
server.ssl.enabled=true
server.error.include-stacktrace=never # no stack traces in responses
server.error.include-exception=false
management.endpoints.web.exposure.include=health,info # not all actuator endpoints
spring.jpa.show-sql=false # no SQL in logs
Database connection security defaults:
# PostgreSQL (psycopg3) — secure connection defaults
import psycopg
conn = psycopg.connect(
conninfo=f"postgresql://{user}:{password}@{host}/{dbname}",
sslmode="require", # enforce TLS
connect_timeout=10, # fail fast, not hang
options="-c statement_timeout=30000" # 30s max query time
)
# SQLAlchemy — pool security settings
from sqlalchemy import create_engine
engine = create_engine(
DATABASE_URL,
pool_pre_ping=True, # verify connection before use
pool_size=10,
max_overflow=20,
pool_timeout=30,
connect_args={
"sslmode": "require",
"connect_timeout": 10,
"options": "-c statement_timeout=30000"
}
)
Infrastructure security defaults checklist:
# Verify security defaults via Django check
python manage.py check --deploy --fail-level WARNING
# Node.js: audit npm packages for known issues with secure defaults
npm audit --audit-level=high
# Scan for security misconfigurations with bandit (Python)
bandit -r src/ -ll # only HIGH and MEDIUM severity
# Check TLS configuration
testssl.sh --severity HIGH --color 0 https://app.company.com
Security defaults checklist for new services:
□ DEBUG=False / equivalent disabled in production
□ HTTPS enforced (redirect + HSTS)
□ Session cookies: Secure + HttpOnly + SameSite=Lax
□ CSRF protection enabled (not disabled)
□ Security headers: X-Frame-Options, X-Content-Type-Options, Referrer-Policy
□ Generic error messages (no stack traces)
□ Database TLS enforced
□ Logging does not include passwords/tokens/PII
□ Dependency versions pinned in lockfile
□ No secrets in environment variables or config files
Rules
- Run
python manage.py check --deploy (Django) or equivalent framework security check before every production deployment — frameworks detect their own misconfigurations.
- Security middleware must run before application code — placing
SecurityMiddleware after custom middleware means requests bypass security headers.
DEBUG = True in production is a critical misconfiguration — Django, Rails, and Flask all expose credentials and internal state in debug mode.
- Default deny for HTTP methods — explicitly allow GET/POST/PUT/DELETE and reject everything else (HEAD, TRACE, CONNECT, OPTIONS unless needed).
Common Mistakes
- Disabling CSRF protection for "convenience" — CSRF protection is disabled per-view as a shortcut in many tutorials; each disabled view is a vulnerability.
SameSite=None cookies without Secure — SameSite=None requires Secure per the spec; without it, the cookie is rejected by modern browsers and the CSRF protection is lost.
- Framework security docs read once, not maintained — security configurations accumulate technical debt; review against current framework documentation at least annually.
- Permissive CSP as a "starting point" —
Content-Security-Policy: default-src * is worse than no CSP because it gives false assurance; start strict and loosen only as needed.
1---2name: apply-secure-defaults3description: Use when configuring a new application, framework, or service — ensuring security is enabled out of the box by setting restrictive defaults for cookies, headers, database connections, and framework security features.4source: 'OWASP Top 10 Proactive Controls C05 C09 (owasp.org/www-project-top-ten/); OWASP Application Security Verification Standard 14.1; CIS Software Supply Chain Security Guide; Django/Rails security configuration documentation'5tags: [security, owasp, secure-defaults, configuration, hardening, framework-security, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-secure-defaults8---910# Apply Secure Defaults1112Configure frameworks and infrastructure with security enabled by default — HttpOnly/Secure/SameSite cookies, HTTPS enforcement, debug disabled, strong cipher suites, and framework security middleware — preventing entire vulnerability classes through configuration rather than per-feature implementation.1314## Why This Is Best Practice1516**Adopted by:** OWASP Top 10 Proactive Controls C05 (Secure By Default Configurations) and C09 (Leverage Security Frameworks and Libraries). Django, Rails, Spring Security, and ASP.NET Core all ship with security defaults that must be explicitly disabled — enabling them is zero-effort compared to implementing the equivalent from scratch. OWASP ASVS 14.1 (Build and Deploy) defines the configuration security requirements. Google's BeyondProd and Netflix's "Paved Road" security model both use security-by-default infrastructure as the primary mechanism for consistent security posture across thousands of services.17**Impact:** The 2021 Log4Shell vulnerability (CVSS 10.0, estimated $6.2B remediation cost) was exploited partly because Java application servers had JNDI lookups enabled by default — disabled by default would have prevented exploitation on most targets without a single line of code change. Django's default `DEBUG = False` in production prevents stack traces from being served to users; teams that deploy with `DEBUG = True` expose full database queries, environment variables, and code to anyone who triggers an error. A CIS Benchmark analysis (2022) found that 65% of remediated cloud misconfigurations were default settings that were never reviewed.18**Why best:** Per-feature security implementation (add CSRF protection here, add XSS escaping there) creates gaps — developers forget or don't know every security requirement. Secure defaults mean a developer who knows nothing about security still gets CSRF protection, secure cookies, and HTTPS enforcement automatically. The alternative (security off by default, enabled per-feature) results in security that's only as good as the developer's security knowledge.1920Sources: OWASP Proactive Controls C05, C09; OWASP ASVS 14.1; Django security documentation; Rails security guide; Netflix Paved Road security model2122## Steps23241. **Django: verify all security middleware and settings are enabled**:2526 ```python27 # settings.py — production security checklist2829 # Run Django's built-in check: python manage.py check --deploy30 # All items below must be verified3132 DEBUG = False # CRITICAL — never True in production3334 ALLOWED_HOSTS = ["app.company.com"] # explicit allowlist, not ["*"]3536 # HTTPS enforcement37 SECURE_SSL_REDIRECT = True38 SECURE_HSTS_SECONDS = 31536000 # 1 year39 SECURE_HSTS_INCLUDE_SUBDOMAINS = True40 SECURE_HSTS_PRELOAD = True4142 # Cookie security43 SESSION_COOKIE_SECURE = True # only over HTTPS44 SESSION_COOKIE_HTTPONLY = True # no JS access45 SESSION_COOKIE_SAMESITE = "Lax" # CSRF protection46 SESSION_COOKIE_AGE = 1800 # 30 min idle timeout47 CSRF_COOKIE_SECURE = True48 CSRF_COOKIE_HTTPONLY = True49 CSRF_COOKIE_SAMESITE = "Lax"5051 # Security middleware (order matters)52 MIDDLEWARE = [53 "django.middleware.security.SecurityMiddleware", # must be first54 "django.middleware.clickjacking.XFrameOptionsMiddleware",55 "django.middleware.csrf.CsrfViewMiddleware",56 # ... other middleware57 ]5859 SECURE_CONTENT_TYPE_NOSNIFF = True60 X_FRAME_OPTIONS = "DENY"61 SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"62 ```63642. **Express.js/Node.js: apply Helmet and secure defaults**:6566 ```javascript67 import express from 'express';68 import helmet from 'helmet';69 import session from 'express-session';7071 const app = express();7273 // Helmet sets 11 security headers in one call74 app.use(helmet({75 contentSecurityPolicy: {76 directives: {77 defaultSrc: ["'self'"],78 scriptSrc: ["'self'"], // no unsafe-inline79 objectSrc: ["'none'"],80 upgradeInsecureRequests: [],81 },82 },83 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },84 }));8586 // Session security87 app.use(session({88 secret: process.env.SESSION_SECRET, // from secrets manager89 name: '__Host-session', // __Host- prefix requires Secure flag90 resave: false,91 saveUninitialized: false,92 cookie: {93 secure: true,94 httpOnly: true,95 sameSite: 'lax',96 maxAge: 30 * 60 * 1000, // 30 minutes97 },98 }));99100 // Disable Express fingerprinting101 app.disable('x-powered-by');102103 // Never serve raw errors in production104 app.use((err, req, res, next) => {105 console.error(err); // log internally106 res.status(500).json({ error: 'Internal server error' }); // generic externally107 });108 ```1091103. **Spring Boot: security configuration baseline**:111112 ```java113 @Configuration114 @EnableWebSecurity115 public class SecurityConfig {116117 @Bean118 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {119 http120 // HTTPS enforcement121 .requiresChannel(channel -> channel.anyRequest().requiresSecure())122 // HSTS123 .headers(headers -> headers124 .httpStrictTransportSecurity(hsts -> hsts125 .maxAgeInSeconds(31536000)126 .includeSubDomains(true)127 .preload(true))128 .contentTypeOptions(Customizer.withDefaults())129 .frameOptions(frame -> frame.deny())130 )131 // Session management132 .sessionManagement(session -> session133 .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)134 .maximumSessions(1)135 .sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)136 )137 // CSRF enabled by default — verify not disabled138 .csrf(Customizer.withDefaults());139 return http.build();140 }141 }142 ```143144 ```properties145 # application-production.properties146 server.ssl.enabled=true147 server.error.include-stacktrace=never # no stack traces in responses148 server.error.include-exception=false149 management.endpoints.web.exposure.include=health,info # not all actuator endpoints150 spring.jpa.show-sql=false # no SQL in logs151 ```1521534. **Database connection security defaults**:154155 ```python156 # PostgreSQL (psycopg3) — secure connection defaults157 import psycopg158159 conn = psycopg.connect(160 conninfo=f"postgresql://{user}:{password}@{host}/{dbname}",161 sslmode="require", # enforce TLS162 connect_timeout=10, # fail fast, not hang163 options="-c statement_timeout=30000" # 30s max query time164 )165166 # SQLAlchemy — pool security settings167 from sqlalchemy import create_engine168169 engine = create_engine(170 DATABASE_URL,171 pool_pre_ping=True, # verify connection before use172 pool_size=10,173 max_overflow=20,174 pool_timeout=30,175 connect_args={176 "sslmode": "require",177 "connect_timeout": 10,178 "options": "-c statement_timeout=30000"179 }180 )181 ```1821835. **Infrastructure security defaults checklist**:184185 ```bash186 # Verify security defaults via Django check187 python manage.py check --deploy --fail-level WARNING188189 # Node.js: audit npm packages for known issues with secure defaults190 npm audit --audit-level=high191192 # Scan for security misconfigurations with bandit (Python)193 bandit -r src/ -ll # only HIGH and MEDIUM severity194195 # Check TLS configuration196 testssl.sh --severity HIGH --color 0 https://app.company.com197 ```198199 ```markdown200 Security defaults checklist for new services:201 □ DEBUG=False / equivalent disabled in production202 □ HTTPS enforced (redirect + HSTS)203 □ Session cookies: Secure + HttpOnly + SameSite=Lax204 □ CSRF protection enabled (not disabled)205 □ Security headers: X-Frame-Options, X-Content-Type-Options, Referrer-Policy206 □ Generic error messages (no stack traces)207 □ Database TLS enforced208 □ Logging does not include passwords/tokens/PII209 □ Dependency versions pinned in lockfile210 □ No secrets in environment variables or config files211 ```212213## Rules214215- Run `python manage.py check --deploy` (Django) or equivalent framework security check before every production deployment — frameworks detect their own misconfigurations.216- Security middleware must run before application code — placing `SecurityMiddleware` after custom middleware means requests bypass security headers.217- `DEBUG = True` in production is a critical misconfiguration — Django, Rails, and Flask all expose credentials and internal state in debug mode.218- Default deny for HTTP methods — explicitly allow GET/POST/PUT/DELETE and reject everything else (HEAD, TRACE, CONNECT, OPTIONS unless needed).219220## Common Mistakes221222- **Disabling CSRF protection for "convenience"** — CSRF protection is disabled per-view as a shortcut in many tutorials; each disabled view is a vulnerability.223- **`SameSite=None` cookies without `Secure`** — `SameSite=None` requires `Secure` per the spec; without it, the cookie is rejected by modern browsers and the CSRF protection is lost.224- **Framework security docs read once, not maintained** — security configurations accumulate technical debt; review against current framework documentation at least annually.225- **Permissive CSP as a "starting point"** — `Content-Security-Policy: default-src *` is worse than no CSP because it gives false assurance; start strict and loosen only as needed.