Skip to main content

REST Security Cheat Sheet

Updated 15 min readMarkdown
REST Security Cheat Sheet

1. Introduction

REST (Representational State Transfer) is an architectural style first described in Roy Fielding's Ph.D. dissertation, Architectural Styles and the Design of Network-based Software Architectures.

REST is widely used for developing distributed hypermedia applications and is most commonly implemented through HTTP-based communication between services.

The key abstraction in REST is a resource, identified by a URI, usually an HTTP URL. REST components use connectors to perform actions on resources by transferring representations of their current or intended state.

The primary connector types are:

  • Client
  • Server

Secondary connector types include:

  • Cache
  • Resolver
  • Tunnel

1.1 Statelessness

REST APIs are stateless. State in REST refers to the state of the resource being accessed, not the state of a client session.

Although stateful APIs may be useful in certain situations, managing sessions introduces additional security complexity.

Passing state from the client to the backend while making the service technically stateless is an anti-pattern that can lead to replay and impersonation attacks.

1.2 Resource Operations

REST APIs commonly support CRUD operations:

  • Create
  • Read
  • Update
  • Delete

For example, an e-commerce application may provide endpoints to:

  1. Create a shopping cart.
  2. Add items to the cart.
  3. Check out the cart.

Each request should independently verify whether the caller is authorized to perform the requested operation.

1.3 HTTP Standards

REST applications use standard HTTP methods and status codes to reduce unnecessary variation between services.

Another important REST concept is HATEOAS (Hypermedia As The Engine of Application State), which allows clients to discover available actions through hypermedia links.

For FastAPI applications, also see the FastAPI Security Cheat Sheet for dependency-based access control, request and response models, and deployment settings.


2. HTTPS

Secure REST services must only provide HTTPS endpoints.

HTTPS provides:

  • Confidentiality of credentials in transit.
  • Authentication of the service to clients.
  • Integrity of transmitted data.

It protects authentication credentials such as passwords, API keys, and JSON Web Tokens.

Consider using mutually authenticated client-side certificates (mTLS) to provide additional protection for highly privileged web services.

See the Transport Layer Security Cheat Sheet for additional information.


3. Access Control

Non-public REST services must perform access control at every API endpoint.

Access control typically involves:

  • User authentication.
  • Authorization logic.
  • Session management, where applicable.

For modern microservice architectures:

  1. Make access control decisions locally at REST endpoints to minimize latency and reduce coupling.
  2. Centralize user authentication in an Identity Provider (IdP).
  3. Use access tokens issued by the IdP.
  4. Ensure every endpoint independently verifies authorization.

For guidance on preventing Insecure Direct Object References (IDOR), see the Insecure Direct Object Reference Prevention Cheat Sheet.


4. JSON Web Tokens (JWT)

JSON Web Tokens are commonly used as security tokens.

JWTs contain claims that can be used for access control decisions. Their integrity can be protected using a cryptographic signature or Message Authentication Code (MAC).

4.1 Protect JWT Integrity

  • Always integrity-protect JWTs using a signature or MAC.
  • Never allow unsecured JWTs using "alg": "none".
  • Prefer digital signatures over MACs for JWT integrity protection.

When MACs are used, every service capable of validating a JWT can also create new JWTs using the same key.

This means:

  • All services sharing the key must mutually trust each other.
  • A compromise of one service can compromise every service sharing that key.

4.2 Validate JWT Claims

The relying party must verify the JWT's integrity and claims.

The verification algorithm must be selected using trusted configuration or hard-coded logic. Never rely on the JWT header to determine the verification algorithm.

For JWTs used for API access control, require and validate the following claims by default:

Claim Validation
iss Verify that the issuer is trusted and owns the signing key.
aud Verify that the API is an intended audience of the token.
exp Verify that the token has not expired.
nbf If present, verify that the token is currently valid.

Require any additional claims mandated by the token profile.

For tokens conforming to RFC 9068, iss, aud, and exp are mandatory.

4.3 JWT Revocation

JWTs may remain valid after a user's session has been terminated.

For example:

  • A user explicitly logs out.
  • An idle session timeout occurs.
  • An administrator terminates a session.

When explicit session termination occurs, a unique, server-issued identifier (jti), optionally combined with aud, should be submitted to a denylist.

The API should reject the revoked JWT until its expiration time.

See the JSON Web Token Cheat Sheet for additional information.


5. API Keys

Public REST services without access control may be abused, leading to excessive bandwidth or compute costs.

API keys can help mitigate this risk and are often used to manage access to paid APIs.

5.1 API Key Security

  • Require API keys for every request to protected endpoints.
  • Return 429 Too Many Requests when clients exceed rate limits.
  • Revoke API keys when clients violate usage agreements.
  • Do not rely exclusively on API keys to protect sensitive, critical, or high-value resources.

API keys issued to third-party clients are relatively easy to compromise.


6. Restrict HTTP Methods

Apply an allowlist of permitted HTTP methods, such as:

  • GET
  • POST
  • PUT

Reject requests using methods outside the allowlist with:

405 Method Not Allowed

Ensure that the caller is authorized to use the requested HTTP method on the:

  • Resource collection.
  • Action.
  • Individual record.

HTTP verb tampering can bypass authentication and authorization when method restrictions are incorrectly implemented.


7. Prevent Out-of-Order API Execution

Modern REST APIs often implement business workflows through a sequence of endpoints.

For example:

Create → Validate → Approve → Finalize

If the backend does not validate workflow state transitions, attackers may invoke endpoints out of sequence to bypass intended controls.

7.1 Problem

Out-of-order API execution occurs when an attacker:

  • Skips required workflow steps by directly calling later-stage endpoints.
  • Replays or reuses tokens across workflow boundaries.
  • Exploits assumptions that the frontend enforces correct sequencing.

Traditional access control checks may fail because each endpoint can be individually authenticated and authorized.

7.2 Example

A checkout workflow expects:

  1. POST /checkout/create
  2. POST /checkout/pay
  3. POST /checkout/confirm

If the backend does not validate workflow state transitions, an attacker could directly invoke:

POST /checkout/confirm

without completing payment.

7.3 Prevention Guidance

  • Enforce workflow state validation on the server side for every request.
  • Model workflows explicitly using finite states or state machines.
  • Bind tokens or identifiers to specific workflow stages.
  • Avoid relying on frontend logic to enforce sequencing.
  • Reject invalid or out-of-order transitions with clear error responses.

7.4 Testing Checklist

  • Can endpoints be invoked out of sequence?
  • Does each endpoint validate the current workflow state?
  • Are tokens reusable across workflow steps?
  • Are invalid state transitions consistently rejected?

8. Input Validation

Never trust input parameters or objects received from clients.

8.1 Validation Requirements

  • Validate input length, range, format, and type.
  • Use strong types such as numbers, booleans, dates, times, and fixed data ranges.
  • Constrain string inputs using regular expressions where appropriate.
  • Reject unexpected or illegal content.
  • Use validation and sanitization libraries or frameworks appropriate to your programming language.

8.2 Request Size Limits

Define an appropriate request size limit.

Reject requests exceeding the configured limit with:

413 Payload Too Large

8.3 Logging Validation Failures

Consider logging input validation failures.

Repeated validation failures, especially hundreds per second, may indicate malicious activity.

8.4 Secure Parsing

Use secure parsers for incoming messages.

If using XML, ensure the parser is not vulnerable to XML External Entity (XXE) attacks or similar vulnerabilities.

See the Input Validation Cheat Sheet for comprehensive guidance.


9. Validate Content Types

REST request and response bodies must match their intended content types.

Incorrect content types can cause misinterpretation by consumers or producers and may lead to code injection or execution.

9.1 Document Supported Content Types

Document all supported content types in your API.

9.2 Validate Request Content Types

For requests with a body:

  • Require a supported Content-Type according to the endpoint contract.
  • Reject unsupported media types with 415 Unsupported Media Type.
  • Do not require Content-Type solely for requests without a body.
  • Reserve 406 Not Acceptable for response content negotiation.

For XML content types, ensure appropriate XML parser hardening.

Explicitly define accepted and produced content types, for example:

@Consumes("application/json")
@Produces("application/json")

This helps prevent unintended content types and reduces potential attack vectors.

9.3 Send Safe Response Content Types

REST services may support multiple response formats, such as:

  • application/json
  • application/xml

Clients can specify their preferences using the Accept header.

Security requirements:

  • Do not copy the Accept header directly into the response Content-Type.
  • Select a supported response type that matches the client's preferences.
  • Respect media ranges and quality values.
  • Return 406 Not Acceptable if no acceptable representation is available and no default representation will be supplied.
  • Ensure the response Content-Type accurately matches the body.

Services returning script code, such as JavaScript, must take particular care to prevent header injection attacks.


10. Management Endpoints

Avoid exposing management endpoints directly to the Internet.

If Internet access is necessary:

  • Require strong authentication, such as multi-factor authentication.
  • Expose management endpoints through separate HTTP ports or hosts.
  • Prefer a separate network interface and restricted subnet.
  • Restrict access using firewall rules or access control lists.

11. Error Handling

Return generic error messages to clients.

Avoid exposing:

  • Call stacks.
  • Internal implementation details.
  • Database errors.
  • Technical information that could help attackers.

Unexpected errors should return an appropriate HTTP status code without revealing sensitive internal information.


12. Audit Logs

Write audit logs before and after security-related events.

Consider logging:

  • Token validation errors.
  • Authentication failures.
  • Authorization failures.
  • Security-sensitive operations.

Sanitize log data to prevent log injection attacks.


13. Security Headers

Security-related HTTP headers instruct browsers how to handle API responses.

Some headers primarily protect HTML responses and may provide little or no security benefit for APIs that never return HTML.

For browser-consumed APIs, consider the following headers.

Header Purpose
Cache-Control: no-store Instructs compliant caches not to store or reuse the response.
Content-Security-Policy: frame-ancestors 'none' Prevents the response from being framed by other domains.
Content-Type Specifies the intended response content type.
Strict-Transport-Security Instructs browsers to use HTTPS for hosts covered by the active HSTS policy.
X-Content-Type-Options: nosniff Prevents browsers from MIME-sniffing responses.
X-Frame-Options: DENY Provides legacy protection against framing and clickjacking.

Important: Cache-Control: no-store does not prevent storage by application code. Sensitive responses must also be kept out of application-managed caches.

HSTS does not protect the initial HTTP connection unless the policy is already known to the browser, such as through preloading.

13.2 Additional Headers for HTML Responses

These headers are primarily relevant when responses are rendered as HTML.

Header Example Purpose
Content-Security-Policy default-src 'none' Restricts resources that an HTML document may load.
Permissions-Policy camera=(), microphone=(), geolocation=() Restricts browser features available to the document.
Referrer-Policy no-referrer Prevents the browser from sending referrer information.

The following is an example of a restrictive Permissions Policy:

Permissions-Policy: accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), navigation-override=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()

Verify that the directives are up to date and appropriate for your application.

If the API never returns HTML, some of these headers may not be necessary. When uncertain, consider including them as part of a defense-in-depth approach.


14. Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is a W3C standard that allows servers to specify which cross-origin requests are permitted.

CORS headers tell browsers which origins are allowed to make JavaScript calls to a REST service.

14.1 CORS Security Requirements

  • Disable CORS headers if cross-origin calls are not supported or expected.
  • Be as specific as possible when configuring allowed origins.
  • Avoid overly permissive origin policies.
  • Allow only the origins required by your application.

15. Sensitive Information in HTTP Requests

RESTful web services must prevent credentials from leaking through URLs.

Passwords, security tokens, and API keys must not appear in URLs because URLs may be captured in web server logs.

15.1 Secure Handling

  • Transfer sensitive data in request bodies or HTTP headers for POST and PUT requests.
  • Transfer sensitive data through HTTP headers for GET requests.
  • Avoid placing credentials in query parameters.

15.2 Examples

OK:

https://example.com/resourceCollection/[ID]/action
https://twitter.com/vanderaj/lists

NOT OK:

https://example.com/controller/123/action?apiKey=a53f435643de32

The API key is exposed in the URL.


16. HTTP Return Codes

Use semantically appropriate HTTP status codes instead of returning 200 OK for every successful request or 404 Not Found for every error.

16.1 HTTP Status Code Reference

Code Message Description
200 OK Successful REST API action.
201 Created Resource created. Return its URI in the Location header.
202 Accepted Request accepted for processing, but processing is incomplete.
301 Moved Permanently Permanent redirection.
304 Not Modified Client already has the current representation.
307 Temporary Redirect Temporary redirection of a resource.
400 Bad Request Malformed request, such as an invalid message body.
401 Unauthorized Missing or invalid authentication credentials.
403 Forbidden Authentication succeeded, but the caller lacks permission.
404 Not Found Requested resource does not exist.
405 Method Not Allowed HTTP method is not supported for the resource.
406 Not Acceptable No supported response representation satisfies the client's preferences.
413 Payload Too Large Request exceeds the configured size limit.
415 Unsupported Media Type Request content format is not supported.
429 Too Many Requests Request rejected due to rate limiting or excessive request frequency.
500 Internal Server Error Unexpected server-side error. Do not reveal internal details.
501 Not Implemented Requested operation is not implemented.
503 Service Unavailable Service temporarily unable to process the request.

16.2 API Key Error Handling

Do not return 200 OK with an empty body when an API key is missing or invalid.

Use:

  • 401 Unauthorized for missing or invalid API keys.
  • 403 Forbidden for valid API keys that lack access to the requested resource.

This allows clients to distinguish authentication failures from successful requests with no data.

Additional information about HTTP status code usage in REST APIs can be found in the relevant HTTP specifications.


17. Security Testing Checklist

Transport Security

  • Does the API enforce HTTPS?
  • Are TLS configurations secure?
  • Is mTLS considered for highly privileged services?

Authentication and Authorization

  • Does every protected endpoint enforce authentication?
  • Is authorization checked independently for each operation?
  • Are JWT signatures and claims validated?
  • Are revoked JWTs rejected?
  • Are API keys properly protected and revocable?

HTTP Methods and Workflows

  • Are unsupported HTTP methods rejected?
  • Is the caller authorized to perform each operation?
  • Are workflow state transitions validated server-side?
  • Are out-of-order requests rejected?

Input and Content Types

  • Are all inputs validated?
  • Are request size limits enforced?
  • Are unsupported content types rejected?
  • Are XML parsers protected against XXE?

Error Handling and Logging

  • Are error messages generic?
  • Are sensitive details excluded from responses?
  • Are security-related events logged?
  • Are log injection attacks prevented?

Browser Security

  • Are appropriate security headers configured?
  • Is CORS restricted to trusted origins?
  • Are credentials excluded from URLs?

18. References

3 views

About the author

No comments yet. Be the first to comment.