REST Security Cheat Sheet / REST安全速查表¶
Introduction / 介绍¶
REST (or REpresentational State Transfer) is an architectural style first described in Roy Fielding's Ph.D. dissertation on Architectural Styles and the Design of Network-based Software Architectures.
It evolved as Fielding wrote the HTTP/1.1 and URI specs and has been proven to be well-suited for developing distributed hypermedia applications. While REST is more widely applicable, it is most commonly used within the context of communicating with services via HTTP.
随着Fielding编写HTTP/1.1和URI规范,REST逐渐发展起来,并已被证明非常适合开发分布式超媒体应用程序。虽然REST应用范围更广,但它最常用于通过HTTP与服务进行通信的上下文中。
The key abstraction of information in REST is a resource. A REST API resource is identified by a URI, usually a HTTP URL. REST components use connectors to perform actions on a resource by using a representation to capture the current or intended state of the resource and transferring that representation.
REST中信息的关键抽象是资源。REST API资源通过URI(通常是一个HTTP URL)进行标识。REST组件使用连接器通过使用表示来捕获资源的当前或预期状态,并将该表示传递到资源上执行操作。
The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.
主要的连接器类型是客户端和服务器,次要连接器包括缓存、解析器和隧道。
REST APIs are stateless. Stateful APIs do not adhere to the REST architectural style. State in the REST acronym refers to the state of the resource which the API accesses, not the state of a session within which the API is called. While there may be good reasons for building a stateful API, it is important to realize that managing sessions is complex and difficult to do securely.
REST API是无状态的。有状态的API不遵循REST架构风格。REST中的状态指的是API访问的资源状态,而不是API调用会话的状态。虽然构建有状态API可能有很好的理由,但重要的是要认识到管理会话既复杂又难以安全地进行。
Stateful services are out of scope of this Cheat Sheet: Passing state from client to backend, while making the service technically stateless, is an anti-pattern that should also be avoided as it is prone to replay and impersonation attacks.
本速查表不涉及有状态服务:从客户端传递状态到后端,虽然从技术上讲服务是无状态的,但这种反模式也应该避免,因为它容易受到重放和冒充攻击。
In order to implement flows with REST APIs, resources are typically created, read, updated and deleted. For example, an ecommerce site may offer methods to create an empty shopping cart, to add items to the cart and to check out the cart. Each of these REST calls is stateless and the endpoint should check whether the caller is authorized to perform the requested operation.
为了实现REST API的流程,通常需要创建、读取、更新和删除资源。例如,一个电子商务网站可能提供创建空购物车、向购物车添加项目和结账购物车的方法。每个REST调用都是无状态的,并且端点应该检查调用者是否有权执行所请求的操作。
Another key feature of REST applications is the use of standard HTTP verbs and error codes in the pursuit or removing unnecessary variation among different services.
REST应用的另一个关键特性是使用标准的HTTP动词和错误代码,以减少不同服务之间的不必要的差异。
Another key feature of REST applications is the use of HATEOAS or Hypermedia As The Engine of Application State. This provides REST applications a self-documenting nature making it easier for developers to interact with a REST service without prior knowledge.
REST应用的另一个关键特性是使用HATEOAS或超媒体作为应用状态引擎。这为REST应用提供了自文档化的特性,使得开发者能够在没有先验知识的情况下更容易地与REST服务交互。
For FastAPI applications, also see the FastAPI Security Cheat Sheet for dependency-based access control, request and response models, and deployment settings.
对于FastAPI应用,还可以参考FastAPI安全备忘录,了解基于依赖的访问控制、请求和响应模型以及部署设置。
HTTPS¶
Secure REST services must only provide HTTPS endpoints. This protects authentication credentials in transit, for example passwords, API keys or JSON Web Tokens. It also allows clients to authenticate the service and guarantees integrity of the transmitted data.
安全的REST服务必须仅提供HTTPS端点。这可以保护传输中的认证凭证,例如密码、API密钥或JSON Web Tokens。它还允许客户端验证服务并保证传输数据的完整性。
See the Transport Layer Security Cheat Sheet for additional information.
有关更多信息,请参阅传输层安全备忘录。
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.
考虑使用相互认证的客户端证书,为高度权限的Web服务提供额外的保护。
Access Control / 访问控制¶
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorization logic and session management. This has several drawbacks for modern architectures which compose multiple microservices following the RESTful style.
非公开REST服务必须在每个API端点执行访问控制。在单体应用中,Web服务通过用户认证、授权逻辑和会话管理来实现这一点。这对于采用RESTful风格的多个微服务组成的现代架构有几个缺点。
- in order to minimize latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints
中文:为了最小化延迟并减少服务之间的耦合,访问控制决策应由REST端点本地进行。 - user authentication should be centralised in a Identity Provider (IdP), which issues access tokens
中文:用户身份验证应集中在一个身份提供者(IdP)中,该提供者颁发访问令牌
For guidance on preventing insecure direct object references (IDOR), see the Insecure Direct Object Reference Prevention Cheat Sheet.
有关防止不安全的直接对象引用(IDOR)的指导,请参阅不安全的直接对象引用预防技巧表。
JWT¶
There seems to be a convergence towards using JSON Web Tokens (JWT) as the format for security tokens. JWTs are JSON data structures containing a set of claims that can be used for access control decisions. A cryptographic signature or message authentication code (MAC) can be used to protect the integrity of the JWT.
似乎正趋向于使用JSON Web Tokens(JWT)作为安全令牌的格式。JWT是包含一组声明的JSON数据结构,可用于访问控制决策。可以使用加密签名或消息认证码(MAC)来保护JWT的完整性。
- Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs:
{"alg":"none"}.
中文:确保JWT通过签名或MAC进行完整性保护。不允许使用不安全的JWT:{"alg":"none"}。 - In general, signatures should be preferred over MACs for integrity protection of JWTs.
中文:通常,对于JWT的完整性保护,应优先选择签名而不是MAC。
If MACs are used for integrity protection, every service that is able to validate JWTs can also create new JWTs using the same key. This means that all services using the same key have to mutually trust each other. Another consequence of this is that a compromise of any service also compromises all other services sharing the same key. See here for additional information.
如果使用MAC进行完整性保护,则能够验证JWT的每个服务也可以使用相同的密钥创建新的JWT。这意味着使用相同密钥的所有服务必须相互信任。这一后果的另一个方面是,任何服务的泄露也会泄露共享相同密钥的所有其他服务。有关更多信息,请参阅此处。
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.
依赖方或令牌消费者通过验证其完整性和包含的声明来验证JWT。
- A relying party must verify the integrity of the JWT based on its own configuration or hard-coded logic. It must not rely on the information of the JWT header to select the verification algorithm. See here and here
中文:依赖方必须根据其自身配置或硬编码的逻辑验证 JWT 的完整性。它不得依赖于 JWT 标头的信息来选择验证算法。参见 此处 和 此处
For JWTs used for API access control, require and validate iss, aud, and exp by default; these claims are mandatory for tokens conforming to RFC 9068, Section 2.2. Require and validate any additional claims that the token profile makes mandatory. Check:
对于用于API访问控制的JWT,默认要求并验证iss、aud和exp;这些声明对于符合RFC 9068第2.2节的令牌是强制性的。要求并验证令牌配置文件中规定的任何附加声明。检查:
issor issuer - is this a trusted issuer? Is it the expected owner of the signing key?
中文:iss或发行者 - 这是一个可信的发行者吗?它是签名密钥的预期所有者吗?audor audience - is the relying party in the target audience for this JWT?
中文:aud或受众 - 这个JWT的目标受众中包含依赖方吗?expor expiration time - is the current time before the end of the validity period of this token?
中文:exp或过期时间 - 当前时间是否在令牌有效期结束之前?nbfor not before time - if present, is the current time at or after the start of the token's validity period? This claim is optional in RFC 7519, Section 4.1.5; require it if the token profile requires it.
中文:nbf或不在时间之前 - 如果存在,是当前时间在令牌有效期开始或之后吗?在 RFC 7519 第 4.1.5 节 中,此声明是可选的;如果令牌配置文件要求,则需要它。
As JWTs contain details of the authenticated entity (user etc.) a disconnect can occur between the JWT and the current state of the users session, for example, if the session is terminated earlier than the expiration time due to an explicit logout or an idle timeout. When an explicit session termination event occurs, a unique, server-issued identifier (the jti claim, optionally combined with aud) should be submitted to a denylist on the API which will invalidate that JWT for any requests until the expiration of the token. See the JSON_Web_Token_Cheat_Sheet for further details.
由于JWT包含已认证实体(用户等)的详细信息,JWT与用户会话的当前状态之间可能会出现断开,例如,如果由于明确的登出或空闲超时而会话在过期时间之前终止。当发生显式会话终止事件时,应将一个唯一的、由服务器颁发的标识符(jti声明,可选地与aud结合)提交到API的拒绝列表中,这将使该JWT在令牌过期之前对任何请求无效。有关详细信息,请参阅JSON_Web_Token_Cheat_Sheet`。
API Keys / API密钥¶
Public REST services without access control run the risk of being farmed leading to excessive bills for bandwidth or compute cycles. API keys can be used to mitigate this risk. They are also often used by organization to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan.
没有访问控制的公共REST服务面临被滥用的风险,这可能导致带宽或计算周期费用过高。API密钥可以用来减轻这种风险。组织也经常使用API密钥来货币化API;而不是阻止高频调用,客户端根据购买的访问计划获得访问权限。
API keys can reduce the impact of denial-of-service attacks. However, when they are issued to third-party clients, they are relatively easy to compromise.
API密钥可以减少拒绝服务攻击的影响。然而,当它们发放给第三方客户端时,相对容易被攻破。
- Require API keys for every request to the protected endpoint.
中文:要求对受保护端点每个请求都需要API密钥。 - Return
429 Too Many RequestsHTTP response code if requests are coming in too quickly.
中文:如果请求来得太快,则返回429 请求过多的HTTP响应代码。 - Revoke the API key if the client violates the usage agreement.
中文:如果客户端违反使用协议,则吊销API密钥。 - Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.
中文:不要仅依赖API密钥来保护敏感、关键或高价值资源。
Restrict HTTP methods / 限制HTTP方法¶
- Apply an allowlist of permitted HTTP Methods e.g.
GET,POST,PUT.
中文:应用允许列表,例如允许的HTTP方法GET、POST、PUT。 - Reject all requests not matching the allowlist with HTTP response code
405 Method not allowed.
中文:对于不匹配允许列表的所有请求,使用HTTP响应代码405 方法不允许进行拒绝。 - Make sure the caller is authorized to use the incoming HTTP method on the resource collection, action, and record
中文:确保调用者有权在资源集合、操作和记录上使用传入的HTTP方法。
In Java EE in particular, this can be difficult to implement properly. See Bypassing Web Authentication and Authorization with HTTP Verb Tampering for an explanation of this common misconfiguration.
在Java EE中,这很难正确实现。参见Bypassing Web Authentication and Authorization with HTTP Verb Tampering以了解这种常见配置错误的解释。
Preventing Out-of-Order API Execution / 防止API执行顺序错误¶
Modern REST APIs often implement business workflows through a sequence of endpoints (for example, create → validate → approve → finalize). If the backend does not explicitly validate workflow state transitions, attackers may invoke endpoints out of sequence to bypass intended controls.
现代REST API通常通过一系列端点(例如,创建→验证→批准→最终确定)实现业务工作流程。如果后端没有明确验证工作流程状态转换,攻击者可能会调用端点以错误的顺序来绕过预期控制。
Problem / 问题¶
Out-of-order API execution occurs when an attacker:
当攻击者时,会发生API执行顺序错误:
- 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
中文:利用前端强制正确排序的假设
Because each endpoint may be individually authenticated and authorized, traditional access control checks often fail to detect these issues.
因为每个端点可能单独进行身份验证和授权,传统的访问控制检查往往无法检测到这些问题。
Example / 示例¶
A checkout workflow expects the following sequence:
结账工作流程期望以下顺序:
POST /checkout/create
POST /checkout/pay
POST /checkout/confirm
If the backend does not validate workflow state transitions, an attacker could directly invoke:
如果后端不验证工作流程状态转换,攻击者可以直接调用:
POST /checkout/confirm
without completing payment.
而不完成支付。
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
中文:明确错误响应,拒绝无效或顺序错误的转换
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?
中文:是否一致地拒绝无效状态转换?
Input validation / 输入验证¶
- Do not trust input parameters/objects.
中文:不要信任输入参数/对象。 - Validate input: length / range / format and type.
中文:验证输入:长度、范围、格式和类型。 - Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters.
中文:通过在API参数中使用强类型(如数字、布尔值、日期、时间或固定数据范围)来实现隐式输入验证。 - Constrain string inputs with regexps.
中文:使用正则表达式约束字符串输入。 - Reject unexpected/illegal content.
中文:拒绝意外/非法内容。 - Make use of validation/sanitation libraries or frameworks in your specific language.
中文:使用您特定语言的验证/清理库或框架。 - Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large.
中文:定义适当的请求大小限制,并使用HTTP响应状态码413(请求实体过大)拒绝超出限制的请求。 - Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.
中文:考虑记录输入验证失败的情况。假设有人每秒进行数百次失败的输入验证,这可能意味着他在做坏事。 - Have a look at input validation cheat sheet for comprehensive explanation.
中文:查看输入验证速查表以获取全面解释。 - Use a secure parser for parsing the incoming messages. If you are using XML, make sure to use a parser that is not vulnerable to XXE and similar attacks.
中文:使用安全的解析器来解析传入的消息。如果您使用 XML,请确保使用不受 XXE 和类似攻击影响的解析器。
Validate content types / 验证内容类型¶
A REST request or response body should match the intended content type in the header. Otherwise this could cause misinterpretation at the consumer/producer side and lead to code injection/execution.
REST请求或响应体应与头部中指定的内容类型匹配。否则,这可能导致消费者/生产者端的误解释,并导致代码注入/执行。
- Document all supported content types in your API.
中文:在您的API中记录所有支持的内容类型。
Validate request content types / 验证请求内容类型¶
- For requests with a body, require a supported
Content-Typeaccording to the endpoint contract and reject unsupported media types with415 Unsupported Media Type. Do not requireContent-Typesolely for requests without a body. Reserve406 Not Acceptablefor response content negotiation.
中文:对于带有主体的请求,根据端点合约要求支持的Content-Type,并拒绝不支持的媒体类型,使用415 不支持的媒体类型(https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.16)响应。对于没有主体的请求,不要要求Content-Type。将406 无法接受保留用于响应内容协商。 - For XML content types ensure appropriate XML parser hardening, see the XXE cheat sheet.
中文:确保对 XML 内容类型使用适当的 XML 解析器加固,参见XXE 欺骗表。 - Avoid accidentally exposing unintended content types by explicitly defining content types e.g. Jersey (Java)
@consumes("application/json"); @produces("application/json"). This avoids XXE-attack vectors for example.
中文:通过显式定义内容类型(例如 Jersey(Java)@consumes("application/json"); @produces("application/json"))来避免意外暴露不期望的内容类型。这避免了 XXE-attack 向量等。
Send safe response content types / 发送安全响应内容类型¶
It is common for REST services to allow multiple response types (e.g. application/xml or application/json, and the client specifies the preferred order of response types by the Accept header in the request.
REST 服务通常允许多种响应类型(例如 application/xml 或 application/json),客户端通过请求中的 Accept 头部指定响应类型的优先顺序。
- Do NOT simply copy the
Acceptheader to theContent-typeheader of the response.
中文:不要简单地将Accept头部复制到响应的Content-type头部。 - Select a supported response type that matches the client's
Acceptpreferences, including media ranges and quality values. If none is acceptable and no default response will be supplied, return406 Not Acceptable.
中文:选择与客户端Accept偏好匹配的响应类型,包括媒体范围和质量值。如果没有可接受的类型,并且没有默认响应将被提供,则返回406 无法接受(https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.7)。
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.
在响应中包含脚本代码(例如 JavaScript)的服务必须特别注意防御头部注入攻击。
- Ensure sending intended content type headers in your response matching your body content e.g.
application/jsonand notapplication/javascript.
中文:确保在响应中发送与您的主体内容匹配的预期内容类型头,例如application/json而不是application/javascript。
Management endpoints / 管理端点¶
- Avoid exposing management endpoints via Internet.
中文:避免通过互联网暴露管理端点。 - If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.
中文:如果管理端点必须通过互联网访问,请确保用户必须使用强认证机制,例如多因素认证。 - Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.
中文:通过不同的 HTTP 端口或主机(最好是不同网卡和受限子网)暴露管理端点。 - Restrict access to these endpoints by firewall rules or use of access control lists.
中文:通过防火墙规则或使用访问控制列表来限制对这些端点的访问。
Error handling / 错误处理¶
- Respond with generic error messages - avoid revealing details of the failure unnecessarily.
中文:返回通用的错误消息 - 避免不必要地泄露失败详情。 - Do not pass technical details (e.g. call stacks or other internal hints) to the client.
中文:不要向客户端传递技术细节(例如调用栈或其他内部提示)。
Audit logs / 审计日志¶
- Write audit logs before and after security related events.
中文:在安全相关事件前后编写审计日志。 - Consider logging token validation errors in order to detect attacks.
中文:考虑记录令牌验证错误以检测攻击。 - Take care of log injection attacks by sanitizing log data beforehand.
中文:通过事先清理日志数据来防范日志注入攻击。
Security Headers / 安全头¶
There are a number of security related headers that can be returned in the HTTP responses to instruct browsers to act in specific ways. However, some of these headers are intended to be used with HTML responses, and as such may provide little or no security benefits on an API that does not return HTML. Note that if the API is only consumed by non-browser clients (e.g. mobile apps, server-to-server calls, command-line tools), most of these headers will have no effect since they are directives for browsers.
The following headers should be included in all API responses that may be consumed by browser clients:
| Header / 头部 | Rationale / 理由 |
|---|---|
Cache-Control: no-store |
Instructs compliant private and shared HTTP caches not to store the response or reuse it for another request (RFC 9111). This does not prevent storage by application code: the Cache API does not honor HTTP caching headers. Keep sensitive responses out of application-managed caches; see the offline application guidance. 指示符合规范的私有和共享 HTTP 缓存不要存储响应或将其用于其他请求 (RFC 9111). 这并不阻止应用程序代码的存储:Cache API 不遵守 HTTP 缓存头。请将敏感响应排除在应用程序管理的缓存之外;参见 离线应用程序指南. |
Content-Security-Policy: frame-ancestors 'none' |
Header used to specify whether a response can be framed in a <frame>, <iframe>, <embed> or <object> element. For an API response, there is no requirement to be framed in any of those elements. Providing frame-ancestors 'none' prevents any domain from framing the response returned by the API call. This header protects against drag-and-drop style clickjacking attacks.用于指定响应是否可以在 <frame>, <iframe>, <embed> 或 <object> 元素中框架的头部。对于 API 响应,没有要求必须在这些元素中框架。提供 frame-ancestors 'none' 防止任何域名框架 API 调用返回的响应。此头部可以防止 拖放 风格的点击劫持攻击。 |
Content-Type |
Header to specify the content type of a response. This must be specified as per the type of content returned by an API call. If not specified or if specified incorrectly, a browser might attempt to guess the content type of the response. This can return in MIME sniffing attacks. One common content type value is application/json if the API response is JSON.用于指定响应内容类型的头部。必须根据 API 调用返回的内容类型进行指定。如果没有指定或指定不正确,浏览器可能会尝试猜测响应的内容类型。这可能导致 MIME 嗅探攻击。如果 API 响应是 JSON,一个常见的类型值是 application/json。 |
Strict-Transport-Security |
For hosts covered by an active HSTS policy, instructs browsers to use HTTPS and terminate connections with TLS errors. Initial HTTP access remains exposed unless policy is already known, such as through preloading. HSTS does not protect against an attacker certificate that the client trusts; see the HSTS threat limitations. 对于受活动HSTS策略覆盖的主机,指示浏览器使用HTTPS并终止TLS错误连接。除非策略已知,例如通过预加载,否则初始HTTP访问仍然暴露。HSTS无法保护客户端信任的攻击者证书;请参阅HSTS威胁限制。 |
X-Content-Type-Options: nosniff |
Header to instruct a browser to always use the MIME type that is declared in the Content-Type header rather than trying to determine the MIME type based on the file's content. This header with a nosniff value prevents browsers from performing MIME sniffing, and inappropriately interpreting responses as HTML.指示浏览器始终使用 Content-Type头中声明的MIME类型,而不是根据文件内容尝试确定MIME类型。此头部的nosniff值阻止浏览器执行MIME嗅探,并错误地将响应解释为HTML。 |
X-Frame-Options: DENY |
Legacy header superseded by Content-Security-Policy: frame-ancestors 'none' (see above). Still recommended for compatibility with older browsers that do not support CSP Level 2. Providing DENY prevents any domain from framing the response.由 Content-Security-Policy: frame-ancestors 'none'(见上文)取代的旧版头部。仍建议与不支持CSP Level 2的旧版浏览器兼容。提供DENY防止任何域名对响应进行框架。 |
The headers below are only intended to provide additional security when responses are rendered as HTML. As such, if the API will never return HTML in responses, then these headers may not be necessary. However, if there is any uncertainty about the function of the headers, or the types of information that the API returns (or may return in future), then it is recommended to include them as part of a defense-in-depth approach.
| Header / 头部 | Example / 示例 | Rationale / 理由 |
|---|---|---|
| Content-Security-Policy | Content-Security-Policy: default-src 'none' |
The majority of CSP functionality only affects pages rendered as HTML. CSP功能的大部分仅影响渲染为HTML的页面。 |
| 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=() |
This header used to be named Feature-Policy. When browsers heed this header, it is used to control browser features via directives. The example disables features with an empty allowlist for a number of permitted directive names. When you apply this header, verify that the directives are up-to-date and fit your needs. Please have a look at this article for a detailed explanation on how to control browser features. 此头部曾命名为Feature-Policy。当浏览器遵守此头部时,它通过指令控制浏览器功能。示例中通过空允许列表禁用了一系列允许的指令名称。应用此头部时,请确保指令是最新的且符合您的需求。请参阅此文章以获取如何控制浏览器功能的详细解释。 |
| Referrer-Policy | Referrer-Policy: no-referrer |
Non-HTML responses should not trigger additional requests. 非 HTML 响应不应触发额外的请求。 |
CORS¶
Cross-Origin Resource Sharing (CORS) is a W3C standard to flexibly specify what cross-domain requests are permitted. By delivering appropriate CORS Headers your REST API signals to the browser which domains, AKA origins, are allowed to make JavaScript calls to the REST service.
- Disable CORS headers if cross-domain calls are not supported/expected.
中文:如果跨域调用不受支持或预期,请禁用 CORS 头部。 - Be as specific as possible and as general as necessary when setting the origins of cross-domain calls.
Sensitive information in HTTP requests / HTTP请求中的敏感信息¶
RESTful web services should be careful to prevent leaking credentials. Passwords, security tokens, and API keys should not appear in the URL, as this can be captured in web server logs, which makes them intrinsically valuable.
RESTful网络服务应小心防止凭证泄露。密码、安全令牌和API密钥不应出现在URL中,因为这可能在网络服务器日志中被捕获,使其具有内在价值。
- In
POST/PUTrequests sensitive data should be transferred in the request body or request headers.
中文:在POST/PUT请求中,敏感数据应通过请求体或请求头部传输。 - In
GETrequests sensitive data should be transferred in an HTTP Header.
中文:在GET请求中,敏感数据应通过HTTP头传输。
OK:
https://example.com/resourceCollection/[ID]/action
https://twitter.com/vanderaj/lists
NOT OK:
https://example.com/controller/123/action?apiKey=a53f435643de32 because the apiKey is in the URL.
https://example.com/controller/123/action?apiKey=a53f435643de32 因为apiKey出现在URL中。
HTTP Return Code¶
HTTP defines status code. When designing REST API, don't just use 200 for success or 404 for error. Always use the semantically appropriate status code for the response.
Here is a non-exhaustive selection of security related REST API status codes. Use it to ensure you return the correct code.
| Code / 代码 | Message / 消息 | Description / 描述 |
|---|---|---|
| 200 | OK | Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. 对成功的 REST API 操作的响应。HTTP 方法可以是 GET、POST、PUT、PATCH 或 DELETE。 |
| 201 | Created 已创建 |
The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. 请求已成功处理并创建了资源。创建的资源 URI 包含在 Location 头部返回。 |
| 202 | Accepted 已接受 |
The request has been accepted for processing, but processing is not yet complete. 请求已被接受处理,但处理尚未完成。 |
| 301 | Moved Permanently 永久重定向 |
Permanent redirection. 永久性重定向。 |
| 304 | Not Modified 未修改 |
Caching related response that returned when the client has the same copy of the resource as the server. 缓存相关响应,当客户端的资源副本与服务器相同返回时。 |
| 307 | Temporary Redirect 临时重定向 |
Temporary redirection of resource. 资源的临时重定向。 |
| 400 | Bad Request 无效请求 |
The request is malformed, such as message body format error. 请求格式错误,例如消息体格式错误。 |
| 401 | Unauthorized 未授权 |
Wrong or no authentication ID/password provided. 提供的认证ID/密码错误或未提供。 |
| 403 | Forbidden 禁止 |
It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource. 当认证成功但认证用户没有请求资源的权限时使用。 |
| 404 | Not Found 未找到 |
When a non-existent resource is requested. 当请求一个不存在的资源时发生。 |
| 405 | Method Not Allowed 方法不允许 |
The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used. 对于意外的 HTTP 方法发生的错误。例如,REST API 期望 HTTP GET,但使用了 HTTP PUT。 |
| 406 | Not Acceptable 不可接受 |
No supported response representation satisfies the client's content negotiation preferences and the server will not send a default representation. 没有支持的响应表示满足客户端的内容协商首选项,服务器将不会发送默认表示。 |
| 413 | Payload too large 负载过大 |
Use it to signal that the request size exceeded the given limit e.g. regarding file uploads. 用它来表示请求大小超过了给定的限制,例如关于文件上传。 |
| 415 | Unsupported Media Type 不支持的媒体类型 |
The request content has a format that the target method does not support. 请求内容格式为目标方法不支持。 |
| 429 | Too Many Requests 请求过多 |
The error is used when there may be DOS attack detected or the request is rejected due to rate limiting. 当检测到可能的拒绝服务攻击或由于速率限制而拒绝请求时使用此错误。 |
| 500 | Internal Server Error 内部服务器错误 |
An unexpected condition prevented the server from fulfilling the request. Be aware that the response should not reveal internal information that helps an attacker, e.g. detailed error messages or stack traces. 一个意外条件阻止服务器满足请求。请注意,响应不应泄露有助于攻击者的内部信息,例如详细的错误消息或堆栈跟踪。 |
| 501 | Not Implemented 未实现 |
The REST service does not implement the requested operation yet. REST服务尚未实现所请求的操作。 |
| 503 | Service Unavailable 服务不可用 |
The REST service is temporarily unable to process the request. Used to inform the client it should retry at a later time. REST服务暂时无法处理请求。用于通知客户端稍后重试。 |
Additional information about HTTP return code usage in REST API can be found here and here.
References / 参考¶
- RFC 8725: JSON Web Token Best Current Practices) (RFC 8725:JSON Web Token 最佳当前实践)
- RFC 9110: HTTP Semantics