Jump to Category
| Authentication & Authorization | Common Vulnerabilities (OWASP) |
| Threat Protection & Design | ⚡ Modern APIs & Protocols |
| Logging & Monitoring |
Authentication & Authorization
1. Compare the OAuth 2.0 Authorization Code grant and the Client Credentials grant. When should each be used?
- Authorization Code Grant: This is a delegated authorization flow used when a user wants to grant a third-party application access to their data on another service. It involves user interaction (login and consent screen) and redirects. The **PKCE** (Proof Key for Code Exchange) extension is now standard for preventing authorization code interception attacks, making it secure for both web and mobile apps. Use this for user-facing applications (e.g., “Log in with Google”).
- Client Credentials Grant: This flow is used for machine-to-machine (M2M) communication. The client authenticates itself directly with the authorization server using its client ID and secret to get an access token. There is no user involved. Use this for backend services, daemons, or CLIs that need to access an API on their own behalf.
2. What is the difference between OAuth 2.0 and OpenID Connect (OIDC)?
They solve different problems, but OIDC is built on top of OAuth 2.0.
- OAuth 2.0 is a framework for **authorization**. It’s about granting a client application permission to access specific resources on behalf of a user. It provides an `access_token`.
- OpenID Connect (OIDC) is a thin layer on top of OAuth 2.0 that adds **authentication**. It provides a standard way to verify a user’s identity and obtain basic profile information. In addition to an `access_token`, it provides an `id_token`, which is a JWT containing claims about the authenticated user (like their ID, email, etc.).
In short: use OAuth 2.0 when you need to access an API. Use OIDC when you need to log a user in.
Explore the OpenID Connect specification.3. What are the most critical security considerations when using JSON Web Tokens (JWTs)?
- Algorithm Choice: Never trust the `alg` header from an incoming JWT. Always enforce a specific, strong asymmetric algorithm (like RS256) on the server side to prevent attackers from switching to a weaker algorithm or `alg: none`.
- Secret Management: For symmetric algorithms (HS256), the secret key must be securely stored and never exposed. For asymmetric algorithms, the private key must be protected.
- Token Revocation: JWTs are stateless and valid until they expire. A strategy for token revocation (e.g., maintaining a blacklist of revoked token IDs) is needed for scenarios like user logout or password change.
- Data Exposure: The payload of a JWS is only Base64 encoded, not encrypted. Do not store sensitive information in the payload unless you are using JWE (JSON Web Encryption).
4. Differentiate between Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC).
- RBAC: Permissions are granted to roles (e.g., `admin`, `editor`, `viewer`), and users are assigned to these roles. The authorization decision is based on “Does this user’s role have permission to perform this action?”. It’s simpler to manage but can be rigid.
- ABAC: Permissions are granted based on a combination of attributes of the user, the resource being accessed, and the environment. Policies are written using these attributes (e.g., “Allow users in the ‘Finance’ department to access documents with the ‘confidential’ tag during business hours”). It is much more flexible and fine-grained than RBAC but more complex to implement.
5. What is the difference between OAuth scopes and application-level permissions?
OAuth scopes** represent the permissions that a *user grants to a client application* to act on their behalf (e.g., `read:profile`, `write:posts`). They define what the application is allowed to do.
Application-level permissions** (or roles) define what a *user themselves* is allowed to do within the application (e.g., `is_admin`, `can_delete_post`).
An API must check both. First, it verifies that the token has the required scope for the requested action. Then, it checks if the user associated with that token has the necessary permissions to perform that action.
6. What is Mutual TLS (mTLS) and when is it used for API security?
Standard TLS secures a connection by having the client verify the server’s certificate. **Mutual TLS** adds a second layer where the server also verifies the client’s certificate. Both parties must present a valid, trusted certificate to establish a connection.
It is used for strong authentication in **service-to-service communication**. In a microservices architecture, mTLS can ensure that only trusted, legitimate services can communicate with each other, providing a high level of security within a service mesh or zero-trust network.
Learn more about Mutual TLS.Common Vulnerabilities (OWASP)
7. What is Broken Object Level Authorization (BOLA) / IDOR and how do you prevent it?
BOLA (Broken Object Level Authorization), also known as IDOR (Insecure Direct Object References), is the most common API vulnerability. It occurs when an API endpoint allows an attacker to access or modify a resource by simply changing the ID in the request, without properly checking if the authenticated user is authorized to access that specific resource.
Prevention: For every single request that accesses a resource by its ID, you must implement a check to verify that the currently authenticated user has ownership or permission to access that specific resource ID. Never trust the ID provided by the client alone.
Read the OWASP guide on BOLA.8. What is Broken Function Level Authorization (BFLA)?
BFLA occurs when an API fails to properly enforce authorization checks for different user roles or groups. For example, a regular user might discover an administrative endpoint like `POST /api/v1/admin/users` and be able to successfully call it because the endpoint itself lacks a proper authorization check to ensure the caller has an `admin` role.
Prevention: Implement a robust authorization layer, often in middleware or decorators, that checks the user’s roles and permissions before allowing access to any sensitive business function or administrative endpoint. Deny by default.
9. What is Mass Assignment and how can you mitigate it?
Mass Assignment is a vulnerability that occurs when a client can provide data that gets automatically bound to an internal object or data model, allowing them to overwrite sensitive, unintended fields. For example, a user might submit a JSON payload `{“email”: “[email protected]”, “isAdmin”: true}` to an update profile endpoint. If the server blindly binds the entire payload to a user object, it might unintentionally promote the user to an administrator.
Mitigation: Avoid binding incoming data directly to internal models. Instead, use Data Transfer Objects (DTOs) that only contain the specific fields you expect and allow to be modified. Maintain a strict allow-list of mutable properties.
10. How do you prevent Injection flaws in an API?
Injection flaws (like SQLi, NoSQLi, Command Injection) occur when untrusted user input is concatenated directly into a query or command.
Prevention:
- Use Parameterized Queries: For SQL, always use prepared statements or ORMs that parameterize inputs. Never use string formatting or concatenation to build queries.
- Sanitize Input: For OS command injection, strictly validate input against an allow-list of characters and use built-in functions that do not invoke a shell.
- Use Safe APIs: Avoid dangerous functions like `eval()` in any language.
11. What is “Excessive Data Exposure”?
This vulnerability occurs when an API returns more data in its response than the client application actually needs or should have access to. Developers often rely on the client-side to filter this data, but an attacker can inspect the raw API response to find sensitive information (e.g., a user object that contains a hashed password or other PII).
Prevention: Implement a transformation layer (like DTOs or GraphQL schemas) on the backend that explicitly defines and exposes only the necessary fields for each API endpoint.
Threat Protection & Design
12. Describe a strategy for API rate limiting.
A common strategy is the **token bucket** or **leaky bucket** algorithm, implemented at the API Gateway or in middleware. For each client (identified by IP, API key, or user ID), you maintain a “bucket” of tokens that replenishes at a fixed rate.
Each API call consumes one token. If the bucket is empty, the request is rejected with a `429 Too Many Requests` status code. This prevents any single client from overwhelming the system with requests. You can also implement different tiers of rate limits for authenticated vs. unauthenticated users.
13. What is the purpose of HTTP security headers like `Content-Security-Policy` and `Strict-Transport-Security`?
- `Content-Security-Policy` (CSP): A powerful header that helps prevent Cross-Site Scripting (XSS). It tells the browser which sources of content (scripts, styles, images) are trusted and allowed to be loaded, effectively creating an allow-list and blocking untrusted assets.
- `Strict-Transport-Security` (HSTS): A header that tells the browser it should only ever communicate with the site using HTTPS, never HTTP. The browser will automatically upgrade any future HTTP requests to HTTPS, preventing protocol downgrade attacks and cookie hijacking.
14. What is Cross-Origin Resource Sharing (CORS) and why is it a security mechanism?
CORS is a browser security mechanism that controls whether a web page running on one origin (domain) is allowed to make requests to an API on a different origin. By default, browsers block these cross-origin requests for security reasons (the Same-Origin Policy).
It’s a security mechanism because it prevents malicious websites from making unauthorized requests to your API from a user’s browser. The API server must explicitly opt-in by sending back CORS headers (like `Access-Control-Allow-Origin`) to tell the browser which origins are permitted to access it.
Learn more about CORS on MDN.15. How would you secure a file upload endpoint?
Securing a file upload endpoint involves multiple layers:
- Authentication/Authorization: Ensure only authenticated and authorized users can upload files.
- Input Validation: Check the file type (using MIME type, not just the extension), enforce size limits, and scan for malware.
- Secure Storage: Do not store uploaded files in the same directory as the application code. Use a separate, non-executable directory or, preferably, a dedicated object storage service like S3 or Azure Blob Storage.
- Safe Serving: Serve user-uploaded content from a different domain than your main application to prevent cookie-based XSS attacks.
16. What is the purpose of an API Gateway?
An API Gateway acts as a single entry point for all API requests. It’s a reverse proxy that sits in front of your backend services and provides a centralized place to handle cross-cutting concerns, such as:
- Request routing to the appropriate microservice.
- Authentication and authorization.
- Rate limiting and throttling.
- Caching and response transformation.
- Logging and monitoring.
Modern APIs & Protocols
17. What are the unique security challenges of GraphQL APIs?
GraphQL’s flexibility introduces unique security challenges not found in traditional REST APIs:
- Complex Query Attacks: Attackers can send deeply nested or resource-intensive queries that can overload the server, leading to a Denial of Service. This is mitigated with query depth limiting and cost analysis.
- Introspection Queries: By default, GraphQL allows clients to query the entire schema. This can be abused by attackers for reconnaissance. This should often be disabled in production.
- Granular Authorization: Authorization needs to be applied at a more granular, per-field level, which is more complex than simply securing an entire REST endpoint.
- Vague Error Messages: Default error messages can sometimes leak information about the underlying schema.
18. How do you secure a WebSocket connection?
Securing a WebSocket involves several steps:
- Use WSS: Always use the `wss://` protocol, which is WebSockets over a secure TLS connection.
- Authentication: Since WebSockets don’t use standard HTTP headers after the initial handshake, authentication is handled differently. A common method is to have the client provide an auth token (like a JWT) as a query parameter during the initial handshake connection. The server validates this token before upgrading the connection.
- Origin Validation: The server should validate the `Origin` header during the handshake to prevent connections from untrusted domains.
- Input Validation: All messages received over the WebSocket must be rigorously validated, just like any other user input.
19. What is Certificate Pinning? What are its pros and cons?
Certificate Pinning is a security mechanism where a client application is configured to only trust a specific server certificate or public key, rather than any certificate signed by a trusted Certificate Authority (CA). Pros:
- It protects against Man-in-the-Middle (MITM) attacks that rely on a compromised CA or a rogue certificate being installed on the user’s device.
- It is very brittle. If the server’s certificate expires or needs to be rotated, you must release a new version of your client application with the new pinned certificate. If you don’t, all existing clients will be unable to connect.
20. What is the difference between a forward proxy and a reverse proxy?
- A Forward Proxy sits in front of a group of client machines. It acts on behalf of the clients and is used by an organization to control and filter its users’ outbound internet traffic.
- A Reverse Proxy sits in front of a group of web servers. It acts on behalf of the servers, intercepting requests from the internet and forwarding them to the appropriate backend server. API Gateways and Load Balancers are types of reverse proxies.
Logging & Monitoring
21. What information should you log for security purposes? What should you explicitly AVOID logging?
You should log:
- Authentication events (successful and failed logins).
- Authorization failures (access denied events).
- High-risk events like password changes or permission changes.
- Input validation failures.
- Key details like the source IP, user agent, timestamp, and user ID for each event.
You must AVOID logging:
- Any form of raw credentials (passwords, API keys, session tokens, JWTs).
- Personally Identifiable Information (PII) like social security numbers, credit card numbers, or health information, unless absolutely necessary and properly secured with access controls.
22. How would you detect a credential stuffing attack against your API?
A credential stuffing attack involves attackers using lists of stolen usernames and passwords to attempt logins. Detection involves monitoring and alerting on specific patterns:
- A high rate of failed login attempts from a single IP address or a range of IPs.
- A high ratio of failed logins to successful logins across the entire system.
- Logins for many different user accounts originating from the same IP address in a short period.
Tools like a WAF, rate limiting, and anomaly detection in your logging system are key to identifying and blocking these attacks.
23. What is a Web Application Firewall (WAF)?
A WAF is a security layer that sits between your users and your API. It inspects HTTP traffic and can block malicious requests based on a set of rules. It’s designed to protect against common web application attacks like SQL injection, Cross-Site Scripting (XSS), and path traversal. Services like AWS WAF or Cloudflare provide managed WAF capabilities.
24. What are some security risks associated with API versioning?
The main risk is **Improper Assets Management**. Teams often focus on securing the latest version (`/api/v2`) but forget about older, deprecated versions (`/api/v1`) that are still running to support legacy clients. These older versions often don’t receive the same security patches and updates, making them a prime target for attackers who can exploit known vulnerabilities. It’s crucial to have a clear plan for deprecating and eventually shutting down old API versions.
25. What is the principle of “deny by default”?
“Deny by default” is a security posture where access is denied unless it has been explicitly granted. In the context of API security, this means that your authorization system should block any request that doesn’t match a specific “allow” rule. This is much safer than an “allow by default” model where you only specify what to block, as you could easily miss a new endpoint or role that needs protection.


