Authentication and security¶
Security is the work of preserving required properties despite mistakes, abuse, and hostile action. It starts with a threat model and ends with evidence that controls work at every boundary.
Use Module 5: Security and correctness for the guided implementation.
Use living guidance
Security recommendations change. Use the current OWASP Cheat Sheet Series, OWASP ASVS, NIST Digital Identity Guidelines, and your platform's maintained documentation for implementation details.
Security properties¶
- confidentiality: information is disclosed only to authorized actors;
- integrity: data and behavior are not changed without authorization;
- availability: required service remains accessible under defined conditions;
- authenticity: an identity, message, or artifact is what it claims to be;
- accountability: relevant actions can be attributed and investigated;
- privacy: personal data is collected and used within stated purpose and policy.
Security goals can conflict. More logging may improve investigation while increasing sensitive-data exposure. State priorities from the system's actual risks.
Threat modeling¶
For each feature:
- identify assets and required properties;
- draw components, data flows, and trust boundaries;
- enumerate actors, entry points, and privileges;
- describe concrete abuse and failure cases;
- select preventive, detective, and recovery controls;
- define tests and operational evidence;
- record deferred risks and revisit conditions.
Threats are contextual. A generic top-ten list helps prompt questions but cannot replace the system model.
Apply least privilege and deny by default. Validate authorization on every request and data operation; one missed path is enough for compromise.
Authentication and authorization¶
Authentication establishes which identity controls an authenticator. Authorization decides whether that actor may perform an operation on a resource. Authentication does not imply broad access.
Keep policy explicit:
actor + action + resource + context → allow or deny
Enforce object ownership or relationship checks at the data-access boundary as well as route-level policy. Derive actor identity from the validated session, never from a request field.
Return behavior should avoid unnecessary resource-existence disclosure. Test horizontal access between two ordinary users, not only unauthenticated and administrator cases.
Passwords and authenticators¶
Do not store plaintext passwords, reversible password encryption, or fast general-purpose password digests.
Use a maintained password-hashing library with a current password-hashing scheme, unique salt, encoded parameters, verification, and rehash support. Follow current OWASP password storage and NIST authenticator guidance for password length, blocklists, rate limiting, and recovery.
Avoid arbitrary composition rules and periodic changes unless a current policy or threat specifically requires them. Never silently trim or truncate a password.
Passwords are not phishing-resistant. For meaningful account risk, prefer mature identity services and phishing-resistant authenticators such as properly implemented WebAuthn/passkeys where appropriate. Recovery must be protected at least as carefully as normal authentication.
Multi-factor authentication combines independent factor categories, such as knowledge and possession. Two knowledge secrets, such as a password and PIN, are not two factors. Prefer phishing-resistant authentication over adding weaker factors solely to satisfy a checkbox.
Throttle guessing with bounded policy that considers account and network signals without enabling permanent attacker-triggered lockout. Keep login errors externally generic and prevent obvious timing differences for unknown accounts.
Sessions¶
A session binds requests to an authenticated identity for a bounded lifetime.
For opaque server-side sessions:
- generate tokens with a cryptographically secure random generator;
- transmit them only over protected channels;
- store a one-way digest rather than the usable token where practical;
- define idle and absolute expiry;
- rotate after privilege changes or authentication events;
- support revocation and logout;
- never place tokens in URLs or logs.
Cookie sessions need secure cookie attributes and CSRF controls. JavaScript-accessible bearer tokens face theft through script compromise. Choose storage and transport from the browser threat model.
JWT is a token format, not an authentication or authorization design. A signed JWT is not encrypted. Validate algorithm policy, issuer, audience, time claims, key selection, and token type. Short lifetime does not solve immediate revocation by itself. Prefer opaque sessions when self-contained tokens provide no measured benefit.
OAuth and OpenID Connect¶
OAuth delegates access authorization. OpenID Connect adds an identity layer. They involve distinct roles, endpoints, tokens, redirect behavior, and threat models.
Use a maintained client/server implementation and the flow recommended for the application type. Validate redirect URIs, state/nonce or equivalent protections, issuer, audience, and PKCE where the current specification and profile require them.
Do not treat an access token as an identity token, accept a token intended for another audience, or invent a simplified OAuth flow from a diagram.
Cryptography¶
Use maintained high-level constructions. Do not design algorithms, modes, padding, nonce formats, or key derivation ad hoc.
| Need | Primitive class |
|---|---|
| Detect accidental corruption | checksum or ordinary hash, depending on threat |
| Store human password verifiers | password-hashing/KDF scheme |
| Authenticate a message with shared secret | MAC |
| Confidentiality and integrity | authenticated encryption (AEAD) |
| Public verification of origin/integrity | digital signature |
| Generate tokens, salts, and nonces | cryptographically secure random generator |
Encryption without authentication can permit undetected modification. Nonce requirements vary by construction and violating them can destroy security.
Key management is usually harder than the cryptographic operation:
- generate keys with approved randomness;
- separate keys by purpose;
- limit access and log administrative use;
- store keys outside application source and artifacts;
- version, rotate, revoke, and recover them;
- destroy keys according to retention and incident policy.
Transport security¶
Use TLS for credentials, tokens, and sensitive application traffic outside an explicitly trusted local boundary. Validate peer identity; encryption to an unauthenticated endpoint is insufficient.
Use current runtime/server defaults and the OWASP TLS guidance. Do not copy static cipher lists into long-lived notes.
TLS protects data in transit between termination points. A reverse proxy that terminates TLS becomes part of the trust boundary, and forwarded identity information must be accepted only from trusted intermediaries.
Input and output boundaries¶
Validation should define allowed shape, type, size, range, encoding, and unknown-field behavior. It improves correctness but does not replace authorization or safe APIs.
Injection¶
Injection occurs when untrusted data becomes executable syntax.
- use parameter binding for SQL;
- pass operating-system commands as argument arrays and avoid a shell;
- use safe template and query APIs;
- allowlist dynamic identifiers that cannot be parameterized;
- avoid evaluating or deserializing untrusted executable formats.
Escaping is context-specific. SQL, shell, HTML, JavaScript, CSS, URL, and log contexts require different handling.
Cross-site scripting¶
Prevent XSS primarily with framework auto-escaping and context-aware output encoding. Avoid inserting untrusted strings into executable JavaScript, raw HTML, or dangerous URL contexts. Sanitization is required only when the product intentionally accepts a restricted HTML subset and must use a maintained sanitizer.
Content Security Policy can reduce impact and provide defense in depth; it does not replace correct encoding.
CSRF¶
CSRF abuses credentials a browser attaches automatically. Use the framework's maintained CSRF protection, appropriate cookie attributes, and origin/token defenses for state-changing requests.
CORS is not a CSRF or authorization control. It governs whether browser scripts may read cross-origin responses.
SSRF¶
Server-side request forgery makes the server fetch attacker-chosen destinations. Prefer not accepting arbitrary destinations. When required, restrict schemes and destinations, resolve and validate addresses carefully, block internal/metadata ranges according to deployment, limit redirects, and enforce network egress policy.
URL parsing and DNS rebinding make string allowlists alone insufficient.
Files and deserialization¶
For file uploads, limit size and count, generate storage names, keep files outside executable paths, validate required content, scan where justified, and authorize every retrieval.
Do not deserialize untrusted data with formats that can construct arbitrary objects or execute code. Use data-only formats with schema and size limits.
API security¶
- authenticate before protected work;
- authorize every object and operation;
- reject unknown or mass-assignable fields;
- bound body, header, query, page, and batch sizes;
- use operation-specific idempotency for unsafe retries;
- apply timeouts and backpressure;
- rate-limit costly or abuse-sensitive actions;
- return stable errors without stack traces or secrets;
- keep internal/admin endpoints separately protected and inventoried.
An unguessable identifier is not authorization. A gateway or firewall does not replace checks inside the application.
Secrets¶
Secrets include credentials, private keys, API tokens, signing keys, recovery codes, and sensitive connection material.
- never commit them to source control or bake them into images;
- inject them through the deployment's secret mechanism;
- validate presence without printing values;
- minimize who and what can read them;
- rotate and revoke through a tested procedure;
- scan source, history, artifacts, logs, and crash reports for leaks;
- treat a committed secret as compromised even after deleting the line.
Environment variables can be a transport mechanism but are not a complete secrets-management lifecycle. Follow current OWASP secrets guidance.
Logging and audit¶
Record authentication outcomes, authorization denials, security-relevant state changes, administrative actions, and control failures.
Include time, event type, outcome, request correlation, actor when known, and target when appropriate. Do not log passwords, raw tokens, authorization headers, private keys, full sensitive bodies, or unnecessary personal data.
Use structured encoding to prevent log injection. Protect logs from unauthorized reading and alteration, define retention, monitor the logging pipeline, and test behavior when required audit writes fail.
Dependencies and delivery¶
Every dependency and build component expands the trusted computing base.
- minimize direct dependencies;
- lock resolved versions and review changes;
- verify source and integrity through the package ecosystem's supported mechanisms;
- pin third-party CI components to reviewed immutable revisions;
- use least-privilege pipeline permissions;
- keep release credentials away from untrusted changes;
- retain source revision, dependency lock, checks, and artifact digest;
- monitor and respond to relevant vulnerability disclosures.
A scanner finding is a prioritization input, not proof of exploitability or safety. Patch decisions need reachability, exposure, impact, compensating controls, and vendor guidance.
Runtime and infrastructure¶
- run as an unprivileged identity;
- separate immutable application content from writable data;
- expose only required ports and paths;
- apply resource and request limits;
- keep host, runtime, and base images patched;
- protect backups and management interfaces;
- fail closed when a security dependency is unavailable unless an explicit risk decision says otherwise;
- test restore and incident procedures.
Containers share the host kernel and do not create a complete security boundary by themselves. Cloud, cluster, and service-mesh features still require application identity and authorization.
Security verification¶
Translate the threat model into executable negative cases:
- unauthenticated access;
- expired, malformed, and revoked credentials;
- cross-user read and mutation;
- injection metacharacters handled as data;
- oversized and malformed inputs;
- duplicate and replayed requests;
- missing configuration and dependency failure;
- secret absence from responses and captured logs;
- backup restore and key/session revocation.
Use the current OWASP ASVS as a verification catalogue appropriate to the application's risk. Do not claim compliance from running a scanner.
Security review belongs throughout design, implementation, review, CI, deployment, and operation. Test controls again when framework, identity, proxy, or storage boundaries change.
Incident readiness¶
Before an incident, define:
- ownership and escalation;
- credential, session, and key revocation;
- evidence preservation and time synchronization;
- containment that avoids unnecessary data loss;
- recovery from verified artifacts and backups;
- communication and disclosure obligations;
- post-incident actions with owners and verification.
Do not wait for compromise to discover that tokens cannot be revoked, logs omit actor identity, or backups cannot be restored.
Review checklist¶
- Are assets and trust boundaries documented?
- Is every protected operation authenticated and authorized?
- Are passwords and sessions handled by maintained implementations?
- Is cryptography high-level with managed keys?
- Are inputs bounded and outputs encoded for their context?
- Are database and command APIs parameterized?
- Are secrets absent from source, artifacts, responses, and logs?
- Are dependencies, CI permissions, and release provenance reviewed?
- Do negative tests cover another ordinary user's access?
- Can credentials be revoked and data be restored during an incident?