Security
305 bites tagged Security — interview questions with model answers, and 60-second explainers.
Handling CORS in Next.js API Routes
CORS isn't a global config; it's a per-route response header. To allow cross-origin requests to your API, you must manually set headers like `Access-Control-Allow-Origin` in your Route Handlers, including handling preflight OPTIONS requests.
React Native Secure Storage: Using Keychain and Keystore
Use the device's native vault (Keychain/Keystore) to store secrets, not plaintext in AsyncStorage. It's for securely persisting small data like API tokens or private keys. The footgun is treating it like a general database; it's slow and for secrets only.
CORSMiddleware: Unblocking Your Frontend from Your Backend
CORS is a browser security rule, not a server bug. Use FastAPI's CORSMiddleware to tell browsers which frontends (e.g., `localhost:3000`) are allowed to fetch data from your API (e.g., `localhost:8000`).
CSRF: Double Submit Cookies for Stateless Backends
Double Submit Cookies stop CSRF by requiring a secret in two places: a cookie and a request header. The server just checks if they match. It's useful for stateless APIs where storing server-side tokens is impractical.
OpenID Connect (OIDC): Authentication as a Service
OIDC lets you delegate user login to a trusted third party, like "Sign in with Google." Your app gets a verifiable token saying who the user is, without handling their password. It's used for SSO in web apps.
Refresh Tokens: Persistent Sessions Without Re-Authentication
A refresh token is a long-lived credential used to get a new, short-lived access token without re-authenticating. It's how apps keep you logged in for weeks. The footgun is storing it insecurely, letting attackers mint access tokens forever.
FastAPI RBAC: Using OAuth2 Scopes for Permissions
Treat OAuth2 scopes as a list of permissions. Instead of checking a user's role, you check if their token has the required scope (e.g., `items:write`) for an endpoint. FastAPI's Security dependency automates this check.
FastAPI: Fine-Grained Permissions with OAuth2 Scopes
Think of OAuth2 scopes as permissions on a keycard. A token gets you in the building, but scopes like `items:read` or `items:write` define which rooms you can enter. Use them in FastAPI to grant granular access.
API Keys: Simple Server-to-Server Authentication
An API key is a simple secret token a client sends to prove its identity, often in a request header. It's ideal for machine-to-machine communication where a user login flow is unnecessary. Footgun: Never send keys in URL query parameters.
HTTP Basic Auth: Simple but Insecure Access Control
HTTP Basic Auth is a simple gatekeeper for your API, prompting users for a username and password directly in the browser. It's useful for internal tools, but never use it over unencrypted HTTP as credentials are sent in a trivially decodable format.
OAuth2 Password Flow: Trading Credentials for a Token
The OAuth2 Password Flow trades a user's credentials for a temporary access token. It's used in trusted first-party apps, like a mobile app logging into its own backend, to avoid sending a password with every API call.
Password Hashing with Python's Passlib
Passlib turns plaintext passwords into secure, salted hashes that are safe to store. Use it in any Python app with user accounts to handle logins. The footgun: never compare hashes directly; always use the `.verify()` method to prevent timing attacks.
FastAPI's Security Utility: Dependencies for Auth
FastAPI's `Security` utility is a specialized `Depends` for authentication. It signals to OpenAPI that a dependency is required for security, enabling interactive docs. Use it to protect endpoints by injecting the authenticated user.
Production Secret Management: Inject, Don't Store
Treat secrets like temporary credentials, injected at runtime, not stored with your code. This applies to database passwords and API keys in production. The biggest footgun is using .env files; they are a dev convenience, not a security model.
JWTs for Stateless API Authentication
JWTs enable stateless authentication: your server verifies users via a self-contained, signed token instead of a session store. This is ideal for distributed APIs. The biggest footgun is storing refresh tokens in localStorage; use HttpOnly cookies instead.
Never Trust Client Input: API Validation
Think of API validation as a bouncer for your server, checking every incoming request's ID before it can access your application logic. Use it in any Express route that accepts user input to prevent bad data from hitting your database or causing errors.
Preventing Sensitive Data Exposure in Node.js
Sensitive data exposure isn't just about database breaches; it's about accidentally leaking secrets. This happens when Node.js apps expose config files, API keys, or raw error messages, often by committing secrets to Git or failing to encrypt data.
HSTS: Forcing Future Connections to Use HTTPS
HSTS is a response header that tells browsers to only use HTTPS for your site, automatically upgrading future HTTP requests. This prevents SSL stripping attacks.
Securing Cookies with HttpOnly, Secure, and SameSite
Think of cookie attributes as security guards for your session data. They prevent common attacks by telling the browser strict rules for sending the cookie, mitigating risks like cross-site scripting (XSS) and cross-site request forgery (CSRF).
Content Security Policy (CSP): An Allowlist for Browser Resources
Content Security Policy is an allowlist you send to the browser, dictating which scripts, styles, and images are safe to load. It's a primary defense against XSS attacks by blocking unauthorized resources.
Dependency Scanning with npm audit
Think of dependency scanning as a background check for your code. `npm audit` compares your project's packages against a database of known security flaws, telling you if you're using vulnerable code. The biggest footgun is blindly running `npm audit fix`.
Preventing SQL Injection: Never Trust User Input
To prevent SQL injection, treat SQL as a template and user input as data that can only fill placeholders, never changing the query's structure. Use this for any database query in your Node.js app that uses external data.
XSS Prevention: Context-Aware Output Encoding
Prevent XSS by encoding all untrusted data just before it's rendered. The key is context: escaping for an HTML body is different from an attribute or script tag. This is critical for displaying user content.
Never Trust User Input: The Validation Mindset
Treat all incoming data as hostile until proven otherwise. Input validation ensures only properly formed data enters your system, protecting against errors and attacks. It applies to user forms, APIs, and partner feeds.
Get Security bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.