<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Yo</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Yo"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Yo"/>
		<updated>2026-05-03T02:17:27Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=240363</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=240363"/>
				<updated>2018-05-02T09:40:26Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* HTTP Return Code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel. 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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Another key feature of REST applications is the use of HATEOS or Hypermedia as the Engine of Application State. This provides REST applications a self-documenting nature making it easier for developer to interact with a REST service without a-priori knowledge.&lt;br /&gt;
&lt;br /&gt;
= HTTPS =&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
= Access Control =&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
= JWT =&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
= API Keys =&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
= Restrict HTTP methods =&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
= Input validation =&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
= Validate content types =&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
== Validate request content types ==&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
== Send safe response content types ==&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
= Management endpoints =&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
= Error handling =&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
= Audit logs =&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
= Security headers =&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
== CORS ==&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Sensitive information in HTTP requests =&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://twitter.com/vanderaj/lists&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/controller/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32 (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
= HTTP Return Code =&lt;br /&gt;
HTTP defines status codes [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Here is a non-exhaustive selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|406&lt;br /&gt;
|Unacceptable&lt;br /&gt;
|The client presented a content type in the Accept header which is not supported by the server API&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|413&lt;br /&gt;
|Payload too large&lt;br /&gt;
|Use it to signal that the request size exceeded the given limit e.g. regarding file uploads&lt;br /&gt;
|-&lt;br /&gt;
|415&lt;br /&gt;
|Unsupported Media Type&lt;br /&gt;
|The requested content type is not supported by the REST service&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|-&lt;br /&gt;
|500 &lt;br /&gt;
|Internal Server Error &lt;br /&gt;
|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.&lt;br /&gt;
|-&lt;br /&gt;
|501&lt;br /&gt;
|Not Implemented&lt;br /&gt;
|The REST service does not implement the requested operation yet&lt;br /&gt;
|-&lt;br /&gt;
|503&lt;br /&gt;
|Service Unavailable&lt;br /&gt;
|The REST service is temporarily unable to process the request. Used to inform the client it should retry at a later time.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235383</id>
		<title>Talk:REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235383"/>
				<updated>2017-11-13T20:15:09Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Protect Session State */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== TODO's from the latest working group (11/2017) ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Avoiding DOR ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
My point with the [[{{PAGENAME}}#Check Authorization for User-Specific Entities|Check Authorization for User-Specific Entities]] section is to avoid Direct Object Reference. There are really two underlying potential pitfalls here:&lt;br /&gt;
* Giving access to objects simply by the key value in the URL rather than checking proper authorization for that entity. (i.e., this user doesn't have access to object 1235, but we allow the method simply because 1235 was in the URL rather than checking to see if '''this''' user is allowed to modify/view it)&lt;br /&gt;
* Giving away sensitive information simply by including the object ID in the URL. Users tend to copy/paste URL's and they get cached in many different places and included in the history (even if the response gives the right &amp;lt;tt&amp;gt;Expires&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;Cache-control&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;Pragma&amp;lt;/tt&amp;gt; headers), so the URL shouldn't directly include anything sensitive like account number. http://some.service/account/128420482 should be a no-no.&lt;br /&gt;
&lt;br /&gt;
== Type Validation ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I would love to add a section on validating incoming entity definitions via XML or JSON. In XML, you have to deal first with entity expansion (death by a million laughs) because entities are expanded '''before''' the XML itself is validated, then need to validate against a DTD, XML-Schema, etc. &lt;br /&gt;
&lt;br /&gt;
I'm just now finding out that there is a loose definition of a JSON validation scheme [http://en.wikipedia.org/wiki/JSON#Schema], but I'm not sure if any of the popular server-side JSON frameworks support this built-in, or what the maturity is of any of the implementations at [http://json-schema.org/implementations.html]. Anybody have any knowledge on this?&amp;lt;br /&amp;gt;&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I was researching between the most popular JavaScript frameworks in order to find a JSON schema validation but it seems that this topic is still immature. But apart from XML and JSON, REST approaches uses syndication feed formats including Atom and RSS.The W3C has a tool for validating those syndication formats.[http://validator.w3.org/feed/#validate_by_uri]&lt;br /&gt;
&lt;br /&gt;
== Payload Attacks ==&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
On top of REST based services,there is a protocol called OData(The Open Data Protocol), OData follows the architectural style of the Web, and allows the HTTP Content negotiation using standard media formats, including XML, JSON, Atom, RSS. Serving data in this formats also increment the risk of payloads attacks. Do you think we should include payloads attacks in this section?&lt;br /&gt;
&lt;br /&gt;
== Authentication in Header ==&lt;br /&gt;
[[User:Chris Harland|Chris H]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I've seen quite a few examples of REST services available over HTTPS where the authentication mechanism (API key or the Username and Password) are added to the Headers of a GET rather than send via cookie or POST, this is TLS encrypted and doesn't suffer the exposure problems of having this information in the URI.  I wondered if anyone had an opinion on this method, good or bad, how could it be exploited?  Could you add something about it to this cheat sheet stating if it is acceptable practice.&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235382</id>
		<title>Talk:REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235382"/>
				<updated>2017-11-13T20:14:30Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Authentication in Header */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== TODO's from the latest working group (11/2017) ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Avoiding DOR ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
My point with the [[{{PAGENAME}}#Check Authorization for User-Specific Entities|Check Authorization for User-Specific Entities]] section is to avoid Direct Object Reference. There are really two underlying potential pitfalls here:&lt;br /&gt;
* Giving access to objects simply by the key value in the URL rather than checking proper authorization for that entity. (i.e., this user doesn't have access to object 1235, but we allow the method simply because 1235 was in the URL rather than checking to see if '''this''' user is allowed to modify/view it)&lt;br /&gt;
* Giving away sensitive information simply by including the object ID in the URL. Users tend to copy/paste URL's and they get cached in many different places and included in the history (even if the response gives the right &amp;lt;tt&amp;gt;Expires&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;Cache-control&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;Pragma&amp;lt;/tt&amp;gt; headers), so the URL shouldn't directly include anything sensitive like account number. http://some.service/account/128420482 should be a no-no.&lt;br /&gt;
&lt;br /&gt;
== Type Validation ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I would love to add a section on validating incoming entity definitions via XML or JSON. In XML, you have to deal first with entity expansion (death by a million laughs) because entities are expanded '''before''' the XML itself is validated, then need to validate against a DTD, XML-Schema, etc. &lt;br /&gt;
&lt;br /&gt;
I'm just now finding out that there is a loose definition of a JSON validation scheme [http://en.wikipedia.org/wiki/JSON#Schema], but I'm not sure if any of the popular server-side JSON frameworks support this built-in, or what the maturity is of any of the implementations at [http://json-schema.org/implementations.html]. Anybody have any knowledge on this?&amp;lt;br /&amp;gt;&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I was researching between the most popular JavaScript frameworks in order to find a JSON schema validation but it seems that this topic is still immature. But apart from XML and JSON, REST approaches uses syndication feed formats including Atom and RSS.The W3C has a tool for validating those syndication formats.[http://validator.w3.org/feed/#validate_by_uri]&lt;br /&gt;
&lt;br /&gt;
== Payload Attacks ==&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
On top of REST based services,there is a protocol called OData(The Open Data Protocol), OData follows the architectural style of the Web, and allows the HTTP Content negotiation using standard media formats, including XML, JSON, Atom, RSS. Serving data in this formats also increment the risk of payloads attacks. Do you think we should include payloads attacks in this section?&lt;br /&gt;
&lt;br /&gt;
== Authentication in Header ==&lt;br /&gt;
[[User:Chris Harland|Chris H]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I've seen quite a few examples of REST services available over HTTPS where the authentication mechanism (API key or the Username and Password) are added to the Headers of a GET rather than send via cookie or POST, this is TLS encrypted and doesn't suffer the exposure problems of having this information in the URI.  I wondered if anyone had an opinion on this method, good or bad, how could it be exploited?  Could you add something about it to this cheat sheet stating if it is acceptable practice.&lt;br /&gt;
&lt;br /&gt;
== Protect Session State ==&lt;br /&gt;
&lt;br /&gt;
[[User:jfalken|Chris Sandulow]]&amp;lt;br /&amp;gt;&lt;br /&gt;
Under 'Protect Session State&amp;quot; I think there should be a short discussion of HMAC'ing anything sent to the client. For stateless applications this especially important; many will encrypted (AES-CBC for example), but not use authenticated encrypted or HMAC the blob. I also posted this on reddit /r/netsec and there is some additional points in that thread --&amp;gt; http://www.reddit.com/r/netsec/comments/2ogjkv/rest_security_cheat_sheet/&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235381</id>
		<title>Talk:REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235381"/>
				<updated>2017-11-13T20:13:15Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Resource protection */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== TODO's from the latest working group (11/2017) ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Avoiding DOR ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
My point with the [[{{PAGENAME}}#Check Authorization for User-Specific Entities|Check Authorization for User-Specific Entities]] section is to avoid Direct Object Reference. There are really two underlying potential pitfalls here:&lt;br /&gt;
* Giving access to objects simply by the key value in the URL rather than checking proper authorization for that entity. (i.e., this user doesn't have access to object 1235, but we allow the method simply because 1235 was in the URL rather than checking to see if '''this''' user is allowed to modify/view it)&lt;br /&gt;
* Giving away sensitive information simply by including the object ID in the URL. Users tend to copy/paste URL's and they get cached in many different places and included in the history (even if the response gives the right &amp;lt;tt&amp;gt;Expires&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;Cache-control&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;Pragma&amp;lt;/tt&amp;gt; headers), so the URL shouldn't directly include anything sensitive like account number. http://some.service/account/128420482 should be a no-no.&lt;br /&gt;
&lt;br /&gt;
== Type Validation ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I would love to add a section on validating incoming entity definitions via XML or JSON. In XML, you have to deal first with entity expansion (death by a million laughs) because entities are expanded '''before''' the XML itself is validated, then need to validate against a DTD, XML-Schema, etc. &lt;br /&gt;
&lt;br /&gt;
I'm just now finding out that there is a loose definition of a JSON validation scheme [http://en.wikipedia.org/wiki/JSON#Schema], but I'm not sure if any of the popular server-side JSON frameworks support this built-in, or what the maturity is of any of the implementations at [http://json-schema.org/implementations.html]. Anybody have any knowledge on this?&amp;lt;br /&amp;gt;&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I was researching between the most popular JavaScript frameworks in order to find a JSON schema validation but it seems that this topic is still immature. But apart from XML and JSON, REST approaches uses syndication feed formats including Atom and RSS.The W3C has a tool for validating those syndication formats.[http://validator.w3.org/feed/#validate_by_uri]&lt;br /&gt;
&lt;br /&gt;
== Payload Attacks ==&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
On top of REST based services,there is a protocol called OData(The Open Data Protocol), OData follows the architectural style of the Web, and allows the HTTP Content negotiation using standard media formats, including XML, JSON, Atom, RSS. Serving data in this formats also increment the risk of payloads attacks. Do you think we should include payloads attacks in this section?&lt;br /&gt;
&lt;br /&gt;
== Authentication in Header ==&lt;br /&gt;
[[User:Chris Harland|Chris H]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I've seen quite a few examples of REST services available over HTTPS where the authentication mechanism (API key or the Username and Password) are added to the Headers of a GET rather than send via cookie or POST, this is TLS encrypted and doesn't suffer the exposure problems of having this information in the URI.  I wondered if anyone had an opinion on this method, good or bad, how could it be exploited?  Could you add something about it to this cheat sheet stating if it is acceptable practice.&lt;br /&gt;
&amp;lt;br/&amp;gt;[[User:Johan Peeters|yo]]&amp;lt;br/&amp;gt;&lt;br /&gt;
I don't agree with the advice that authentication should be session-based.&lt;br /&gt;
I would avoid keeping track of sessions on the server side if at all possible and require the client to pass a security token, e.g. OIDC JWT, in the Authorization header with each request. Thoughts anyone?&lt;br /&gt;
&lt;br /&gt;
== Protect Session State ==&lt;br /&gt;
&lt;br /&gt;
[[User:jfalken|Chris Sandulow]]&amp;lt;br /&amp;gt;&lt;br /&gt;
Under 'Protect Session State&amp;quot; I think there should be a short discussion of HMAC'ing anything sent to the client. For stateless applications this especially important; many will encrypted (AES-CBC for example), but not use authenticated encrypted or HMAC the blob. I also posted this on reddit /r/netsec and there is some additional points in that thread --&amp;gt; http://www.reddit.com/r/netsec/comments/2ogjkv/rest_security_cheat_sheet/&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235380</id>
		<title>Talk:REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:REST_Security_Cheat_Sheet&amp;diff=235380"/>
				<updated>2017-11-13T20:12:33Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* REST short definition */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== TODO's from the latest working group (11/2017) ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Avoiding DOR ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
My point with the [[{{PAGENAME}}#Check Authorization for User-Specific Entities|Check Authorization for User-Specific Entities]] section is to avoid Direct Object Reference. There are really two underlying potential pitfalls here:&lt;br /&gt;
* Giving access to objects simply by the key value in the URL rather than checking proper authorization for that entity. (i.e., this user doesn't have access to object 1235, but we allow the method simply because 1235 was in the URL rather than checking to see if '''this''' user is allowed to modify/view it)&lt;br /&gt;
* Giving away sensitive information simply by including the object ID in the URL. Users tend to copy/paste URL's and they get cached in many different places and included in the history (even if the response gives the right &amp;lt;tt&amp;gt;Expires&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;Cache-control&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;Pragma&amp;lt;/tt&amp;gt; headers), so the URL shouldn't directly include anything sensitive like account number. http://some.service/account/128420482 should be a no-no.&lt;br /&gt;
&lt;br /&gt;
== Type Validation ==&lt;br /&gt;
[[User:Will Stranathan|Will]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I would love to add a section on validating incoming entity definitions via XML or JSON. In XML, you have to deal first with entity expansion (death by a million laughs) because entities are expanded '''before''' the XML itself is validated, then need to validate against a DTD, XML-Schema, etc. &lt;br /&gt;
&lt;br /&gt;
I'm just now finding out that there is a loose definition of a JSON validation scheme [http://en.wikipedia.org/wiki/JSON#Schema], but I'm not sure if any of the popular server-side JSON frameworks support this built-in, or what the maturity is of any of the implementations at [http://json-schema.org/implementations.html]. Anybody have any knowledge on this?&amp;lt;br /&amp;gt;&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I was researching between the most popular JavaScript frameworks in order to find a JSON schema validation but it seems that this topic is still immature. But apart from XML and JSON, REST approaches uses syndication feed formats including Atom and RSS.The W3C has a tool for validating those syndication formats.[http://validator.w3.org/feed/#validate_by_uri]&lt;br /&gt;
&lt;br /&gt;
== Payload Attacks ==&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
On top of REST based services,there is a protocol called OData(The Open Data Protocol), OData follows the architectural style of the Web, and allows the HTTP Content negotiation using standard media formats, including XML, JSON, Atom, RSS. Serving data in this formats also increment the risk of payloads attacks. Do you think we should include payloads attacks in this section?&lt;br /&gt;
&lt;br /&gt;
== Resource protection ==&lt;br /&gt;
[[User:Michael Hidalgo|Michael]]&amp;lt;br /&amp;gt;&lt;br /&gt;
In HTTP, the centric piece of functionality is a resource. So it is very important that only those authorized guys can access to each resource(if the guy does not have permision, a HTTP status code should be displayed 401 unauthorized. Also it is important to use SSL for all HTTP traffic. Does that make sense as a part of this Cheat Sheet?&lt;br /&gt;
&lt;br /&gt;
== Authentication in Header ==&lt;br /&gt;
[[User:Chris Harland|Chris H]]&amp;lt;br /&amp;gt;&lt;br /&gt;
I've seen quite a few examples of REST services available over HTTPS where the authentication mechanism (API key or the Username and Password) are added to the Headers of a GET rather than send via cookie or POST, this is TLS encrypted and doesn't suffer the exposure problems of having this information in the URI.  I wondered if anyone had an opinion on this method, good or bad, how could it be exploited?  Could you add something about it to this cheat sheet stating if it is acceptable practice.&lt;br /&gt;
&amp;lt;br/&amp;gt;[[User:Johan Peeters|yo]]&amp;lt;br/&amp;gt;&lt;br /&gt;
I don't agree with the advice that authentication should be session-based.&lt;br /&gt;
I would avoid keeping track of sessions on the server side if at all possible and require the client to pass a security token, e.g. OIDC JWT, in the Authorization header with each request. Thoughts anyone?&lt;br /&gt;
&lt;br /&gt;
== Protect Session State ==&lt;br /&gt;
&lt;br /&gt;
[[User:jfalken|Chris Sandulow]]&amp;lt;br /&amp;gt;&lt;br /&gt;
Under 'Protect Session State&amp;quot; I think there should be a short discussion of HMAC'ing anything sent to the client. For stateless applications this especially important; many will encrypted (AES-CBC for example), but not use authenticated encrypted or HMAC the blob. I also posted this on reddit /r/netsec and there is some additional points in that thread --&amp;gt; http://www.reddit.com/r/netsec/comments/2ogjkv/rest_security_cheat_sheet/&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233300</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233300"/>
				<updated>2017-09-14T07:31:32Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Sensitive information in HTTP requests */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/controller/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32 (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here is a selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|406&lt;br /&gt;
|Unacceptable&lt;br /&gt;
|The client presented a content type in the Accept header which is not supported by the server API&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|413&lt;br /&gt;
|Payload too large&lt;br /&gt;
|Use it to signal that the request size exceeded the given limit e.g. regarding file uploads&lt;br /&gt;
|-&lt;br /&gt;
|415&lt;br /&gt;
|Unsupported Media Type&lt;br /&gt;
|The requested content type is not supported by the REST service&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233269</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233269"/>
				<updated>2017-09-13T19:15:57Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* HTTP Return Code */  additional codes&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here is a selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|406&lt;br /&gt;
|Unacceptable&lt;br /&gt;
|The client presented a content type in the Accept header which is not supported by the server API&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|413&lt;br /&gt;
|Payload too large&lt;br /&gt;
|Use it to signal that the request size exceeded the given limit e.g. regarding file uploads&lt;br /&gt;
|-&lt;br /&gt;
|415&lt;br /&gt;
|Unsupported Media Type&lt;br /&gt;
|The requested content type is not supported by the REST service&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233268</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233268"/>
				<updated>2017-09-13T19:11:12Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: removed redundant listing of other cheat sheets&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here is a selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233267</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233267"/>
				<updated>2017-09-13T19:09:29Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: removed duplicate /* Authors and primary editors */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here is a selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233266</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233266"/>
				<updated>2017-09-13T18:50:41Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* HTTP Return Code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here is a selection of security related REST API status codes. Use it to ensure you return the correct code.   &lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Status code&lt;br /&gt;
!Message&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|200&lt;br /&gt;
|OK&lt;br /&gt;
|Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE&lt;br /&gt;
|-&lt;br /&gt;
|201&lt;br /&gt;
|Created&lt;br /&gt;
|The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header&lt;br /&gt;
|-&lt;br /&gt;
|202&lt;br /&gt;
|Accepted&lt;br /&gt;
|The request has been accepted for processing, but processing is not yet complete&lt;br /&gt;
|-&lt;br /&gt;
|400&lt;br /&gt;
|Bad Request&lt;br /&gt;
|The request is malformed, such as message body format error&lt;br /&gt;
|-&lt;br /&gt;
|401&lt;br /&gt;
|Unauthorized&lt;br /&gt;
|Wrong or no authentication ID/password provided&lt;br /&gt;
|-&lt;br /&gt;
|403&lt;br /&gt;
|Forbidden&lt;br /&gt;
|It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
|-&lt;br /&gt;
|404&lt;br /&gt;
|Not Found&lt;br /&gt;
|When a non-existent resource is requested&lt;br /&gt;
|-&lt;br /&gt;
|405&lt;br /&gt;
|Method Not Allowed&lt;br /&gt;
|The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used&lt;br /&gt;
|-&lt;br /&gt;
|429&lt;br /&gt;
|Too Many Requests&lt;br /&gt;
|The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233261</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233261"/>
				<updated>2017-09-13T16:53:06Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: rewrite during the cheat sheet workshop&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233259</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233259"/>
				<updated>2017-09-13T15:42:07Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: removed JWT validation header&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233258</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233258"/>
				<updated>2017-09-13T15:40:38Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: to do: mention OAuth and OIDC&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
* a client can obtain security tokens by doing an OAuth or OIDC dance with an authZ server&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233257</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233257"/>
				<updated>2017-09-13T15:33:39Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: To do list&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== To do ==&lt;br /&gt;
* describe the scope of the cheat sheet more clearly&lt;br /&gt;
** server to server calls is a special case&lt;br /&gt;
* coarse- vs fine-grained authZ&lt;br /&gt;
* token usage scenario's&lt;br /&gt;
** short lived&lt;br /&gt;
** bearer&lt;br /&gt;
* limitations and mitigations of bearer tokens&lt;br /&gt;
* secrets mgmt&lt;br /&gt;
** JWK&lt;br /&gt;
** key management&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233256</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233256"/>
				<updated>2017-09-13T15:06:08Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Authors and primary editors */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233255</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233255"/>
				<updated>2017-09-13T15:05:06Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey] (Java) ''@consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233242</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233242"/>
				<updated>2017-09-13T09:35:36Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Confidentiality */  renamed&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Sensitive information in HTTP requests ==&lt;br /&gt;
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.&lt;br /&gt;
* In POST/PUT requests sensitive data should be transferred in the request body or request headers&lt;br /&gt;
* In GET requests sensitive data should be transferred in an HTTP Header&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;nowiki&amp;gt;https://example.com/resourceCollection/&amp;lt;/nowiki&amp;gt;&amp;lt;id&amp;gt;/action&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233241</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233241"/>
				<updated>2017-09-13T09:32:05Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: Management endpoints&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Management endpoints ==&lt;br /&gt;
* Avoid exposing management endpoints via Internet.&lt;br /&gt;
* If management endpoints must be accessible via the Internet, make sure that users must use a strong authentication mechanism, e.g. multi-factor.&lt;br /&gt;
* Expose management endpoints via different HTTP ports or hosts preferably on a different NIC and restricted subnet.&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or use of access control lists.&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
== Authors and primary editors  ==&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233240</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233240"/>
				<updated>2017-09-13T09:18:31Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* API Keys */  part of access control&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== API Keys ===&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect sensitive, critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233239</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233239"/>
				<updated>2017-09-13T09:16:07Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* API Keys */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
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 organisation to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance to a purchased access plan. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
* Require API keys for every request to the protected endpoint.&lt;br /&gt;
* Return 429 &amp;quot;Too Many Requests&amp;quot; HTTP response code if requests are coming in too quickly.&lt;br /&gt;
* Revoke the API key if the client violates the usage agreement.&lt;br /&gt;
* Do not rely exclusively on API keys to protect critical or high-value resources.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233238</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233238"/>
				<updated>2017-09-13T08:46:46Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* CORS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
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.&lt;br /&gt;
* Disable CORS headers if cross-domain calls are not supported&lt;br /&gt;
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls &lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;https://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-methods=GET,POST&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233179</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233179"/>
				<updated>2017-09-12T14:02:48Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
Cross-Origin Resource Sharing (CORS) is a W3C standard to flexibly specify what kind of 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 your REST service.&lt;br /&gt;
* Disable CORS headers if you don’t want to support cross domain calls&lt;br /&gt;
* Make sure to explicitly name the domains you want to support&lt;br /&gt;
In Spring Boot (Java), for example, CORS support is disabled by default and is only enabled once the ''endpoints.cors.allowed-origins'' property has been set. The configuration below permits GET and POST calls from the example.com domain:&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;http://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&amp;lt;blockquote&amp;gt;endpoints.cors.allowed-origins=&amp;lt;nowiki&amp;gt;http://example.com&amp;lt;/nowiki&amp;gt;&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233178</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233178"/>
				<updated>2017-09-12T13:24:28Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 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.  &lt;br /&gt;
* Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {&amp;quot;alg&amp;quot;:&amp;quot;none&amp;quot;}. See https://tools.ietf.org/html/rfc7519#section-6.1&lt;br /&gt;
* In general, signatures should be preferred over MACs for integrity protection of JWTs.&lt;br /&gt;
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 https://tools.ietf.org/html/rfc7515#section-10.5 for additional information.&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its integrity and claims contained.&lt;br /&gt;
* 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 https://www.chosenplaintext.ca/2015/03/31/jwt-algorithm-confusion.html and https://www.youtube.com/watch?v=bW5pS4e_MX8&lt;br /&gt;
Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233177</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233177"/>
				<updated>2017-09-12T13:00:53Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: authors and editors&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are integrity protected by a signature or a MAC&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Jan Wolff - jan.wolff@owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Rocco Gränitz - rocco.graenitz@mailbox.org&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233176</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233176"/>
				<updated>2017-09-12T12:55:51Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are integrity protected by a signature or a MAC&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate business API endpoints from management endpoints ==&lt;br /&gt;
* Expose management endpoints via different HTTP ports preferably on a different NIC and restricted subnet&lt;br /&gt;
* Restrict access to these endpoints by firewall rules  or usage of access control lists&lt;br /&gt;
&lt;br /&gt;
== Error handling ==&lt;br /&gt;
* Respond with generic error messages - avoid revealing details of the failure unnecessarily&lt;br /&gt;
* Do not pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Audit logs ==&lt;br /&gt;
* Write audit logs before and after security related events&lt;br /&gt;
* Consider logging token validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitising log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233174</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233174"/>
				<updated>2017-09-12T10:14:39Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are integrity protected by a signature or a MAC&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Restrict HTTP methods ==&lt;br /&gt;
* Apply a whitelist of permitted HTTP Methods e.g. GET, POST, PUT&lt;br /&gt;
&lt;br /&gt;
* Reject all requests not matching the whitelist with HTTP response code 405 Method not allowed&lt;br /&gt;
* Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Separate public business api endpoints from management endpoints ==&lt;br /&gt;
* Expose Management Endpoints via different HTTP ports&lt;br /&gt;
* Restrict Access to these endpoints by Firewall Rules  or usage of Access Control Lists&lt;br /&gt;
&lt;br /&gt;
== Exception Handling/Management ==&lt;br /&gt;
* Respond with common error messages&lt;br /&gt;
* Don’t pass technical details (e.g. call stacks or other internal hints) to the client&lt;br /&gt;
&lt;br /&gt;
== Auditing/ Logging ==&lt;br /&gt;
* Write audit logs before/after security related events&lt;br /&gt;
* Consider Logging validation errors in order to detect attacks&lt;br /&gt;
* Take care of log injection attacks by sanitizing log data beforehand&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233173</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233173"/>
				<updated>2017-09-12T09:50:52Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Input validation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are integrity protected by a signature or a MAC&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters&lt;br /&gt;
* Constrain string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.&lt;br /&gt;
* Have a look at input validation cheat sheet for comprehensive explanation&lt;br /&gt;
&lt;br /&gt;
* 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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
== Validate content types ==&lt;br /&gt;
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.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
&lt;br /&gt;
=== Validate request content types ===&lt;br /&gt;
* Reject requests containing unexpected or missing content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. [https://jersey.github.io/ Jersey]''@(Java)consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;)''. This avoids XXE-attack vectors for example.&lt;br /&gt;
&lt;br /&gt;
=== Send safe response content types ===&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;quot;application/xml&amp;quot; or &amp;quot;application/json&amp;quot;, and the client specifies the preferred order of response types by the Accept header in the request. &lt;br /&gt;
* Do NOT simply copy the Accept header to the Content-type header of the response. &lt;br /&gt;
* Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.&lt;br /&gt;
Services including script code (e.g. JavaScript) in their responses must be especially careful to defend against header injection attack.&lt;br /&gt;
* ensure sending intended content type headers in your response matching your body content e.g. &amp;quot;application/json&amp;quot; and not &amp;quot;application/javascript&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233172</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233172"/>
				<updated>2017-09-12T09:19:13Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: removed section on externalising IdP and STS&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are integrity protected by a signature or a MAC&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
A REST request or response body should match the advertised content-type in the header.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
* Reject requests containing unexpected content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
* Ensure content type headers in your response match the body content&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. @consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;). This avoid XXE-attack vectors for example. &lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, dates, times in API parameters&lt;br /&gt;
* Sanitize string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good. &lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233171</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233171"/>
				<updated>2017-09-12T09:00:46Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* JWT validation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorisation logic and session management. This has several drawbacks for modern architectures which compose multiple micro services following the RESTful style. &lt;br /&gt;
* in order to minimise latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints&lt;br /&gt;
* user authentication should be centralised in a Identity Provider (IdP), which issues access tokens&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
There seems to be a convergence towards using [https://tools.ietf.org/html/rfc7519 JSON Web Tokens] (JWT) as the format for security tokens. JWTs contain a set of claims that can be used for access control decisions. &lt;br /&gt;
* Ensure JWTs are signed&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
The relying party or token consumer validates a JWT by verifying its signature and claims contained. Some claims have been standardised and should be present in JWT used for access controls. At least the following of the standard claims should be verified:&lt;br /&gt;
* 'iss' or issuer - is this a trusted issuer? Is it the expected owner of the signing key?&lt;br /&gt;
* 'aud' or audience - is the relying party in the target audience for this JWT?&lt;br /&gt;
* 'exp' or expiration time - is the current time before the end of the validity period of this token?&lt;br /&gt;
* 'nbf' or not before time - is the current time after the start of the validity period of this token?&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
A REST request or response body should match the advertised content-type in the header.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
* Reject requests containing unexpected content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
* Ensure content type headers in your response match the body content&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. @consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;). This avoid XXE-attack vectors for example. &lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, dates, times in API parameters&lt;br /&gt;
* Sanitize string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good. &lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233169</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233169"/>
				<updated>2017-09-12T07:28:34Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: structure&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== JWT ===&lt;br /&gt;
&lt;br /&gt;
==== JWT validation ====&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
A REST request or response body should match the advertised content-type in the header.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
* Reject requests containing unexpected content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
* Ensure content type headers in your response match the body content&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. @consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;). This avoid XXE-attack vectors for example. &lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, dates, times in API parameters&lt;br /&gt;
* Sanitize string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good. &lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233149</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233149"/>
				<updated>2017-09-11T19:23:26Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Content types */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
A REST request or response body should match the advertised content-type in the header.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
* Reject requests containing unexpected content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
* Ensure content type headers in your response match the body content&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
* Avoid accidentally exposing unintended content types by explicitly defining content types e.g. @consumes(&amp;quot;application/json&amp;quot;); @produces(&amp;quot;application/json&amp;quot;). This avoid XXE-attack vectors for example. &lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, dates, times in API parameters&lt;br /&gt;
* Sanitize string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good. &lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233148</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233148"/>
				<updated>2017-09-11T19:18:40Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: /* Input validation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
A REST request or response body should match the advertised content-type in the header.&lt;br /&gt;
* Document all supported content types in your API&lt;br /&gt;
* Reject requests containing unexpected content type headers with HTTP response status 406 Unacceptable or 415 Unsupported Media Type&lt;br /&gt;
* Ensure content type headers in your response match the body content&lt;br /&gt;
* Explicitly define content-types e.g. @consumes(&amp;quot;application/json&amp;quot;); @consumes(&amp;quot;application/json&amp;quot;)&lt;br /&gt;
* For XML content types ensure appropriate XML parser hardening, see the [[XML External Entity (XXE) Prevention Cheat Sheet|cheat shee]]&amp;lt;nowiki/&amp;gt;t&lt;br /&gt;
* Do not accidentally expose unintended content types e.g. XML (XXE-attack vectors)&lt;br /&gt;
**&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
* Do not trust input parameters/objects&lt;br /&gt;
* Validate input: length / range / format and type&lt;br /&gt;
* Achieve an implicit input validation by using strong types like numbers, dates, times in API parameters&lt;br /&gt;
* Sanitize string inputs with regexps&lt;br /&gt;
* Reject unexpected/illegal content&lt;br /&gt;
* Make use of validation/sanitation libraries or frameworks in your specific language&lt;br /&gt;
* Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large&lt;br /&gt;
* Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good. &lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233147</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233147"/>
				<updated>2017-09-11T17:02:04Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: HTTPS&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== HTTPS ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
See the [[Transport Layer Protection Cheat Sheet]] for additional information.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233146</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233146"/>
				<updated>2017-09-11T16:51:16Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: Structure&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
== Whitelist HTTP methods ==&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
== API Keys ==&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== API rate limits ===&lt;br /&gt;
The objectives of API Rate is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Content types ==&lt;br /&gt;
&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
== Security headers ==&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== CORS ===&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233145</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233145"/>
				<updated>2017-09-11T16:09:14Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: removed material that is out of scope or wrong&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols such as OAuth 2.0 and OpenID Connect (OIDC) rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful APIs expose resources that can be acted upon by HTTP verbs such as GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233144</id>
		<title>Draft REST cheat sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Draft_REST_cheat_sheet&amp;diff=233144"/>
				<updated>2017-09-11T15:50:40Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: Created page with &amp;quot; __NOTOC__ &amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;link=&amp;lt;/div&amp;gt;  {| style=&amp;quot;padding: 0;margin:0;margin-top:10px;...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Basic Authentication does not provide a mechanism for logging the user out. Credentials are cached in the browser and re-submitted with subsequent requests. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant or secure design. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, authN/Z technologies should at least&lt;br /&gt;
* limit the scope of access rights granted to the client,&lt;br /&gt;
* limit access rights in time,&lt;br /&gt;
* avoid exposing user credentials to the client,&lt;br /&gt;
* support multi-factor authentication.&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which it could impersonate the resource owner. Instead of users having to completely trust the client, they can, and should, limit the privileges they grant the client to those needed for the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties,  &lt;br /&gt;
* the resource owner or user,  &lt;br /&gt;
* the user agent, e.g. the browser,  &lt;br /&gt;
* the client, e.g. a Single Page Application implemented in JavaScript and running in the browser,  &lt;br /&gt;
* the authorization server and  &lt;br /&gt;
* the resource server, or, in other words, the REST API.  &lt;br /&gt;
In the 4th grant type, resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
Neither in the Authorization Code nor in the Implicit Grant are client credentials handed to the client: when an access token is required, the client redirects the user agent to the authorization server. If the resulting interaction between resource owner and authorization server completes successfully, the user is redirected back to the client with a token which can be used to unlock access to resource servers. &lt;br /&gt;
&lt;br /&gt;
On the other hand, when the Resource Owner Password or Client Credentials Grant, resource owner credentials are exposed to the client. Hence it has been argued that these grant types do not afford better protection than Basic Authentication. Nonetheless, their use is a step in the right direction. &lt;br /&gt;
&lt;br /&gt;
In the past, OAuth has frequently been misused for authentication. With the increasingly widespread adoption and tool support for OpenID Connect, the temptation to do so has diminished. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is built on OAuth 2.0 and is widely used for authentication. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
Conventional wisdom says that authorization follows authentication - before granting permission, you need to know who is asking. OpenID Connect turns this on its head: it considers identity information as a resource and for the client to access it, the user, who is also the owner of these identity resources, must grant permission.&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233126</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233126"/>
				<updated>2017-09-11T06:41:20Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Basic Authentication does not provide a mechanism for logging the user out. Credentials are cached in the browser and re-submitted with subsequent requests. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant or secure design. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, authN/Z technologies should at least&lt;br /&gt;
* limit the scope of access rights granted to the client,&lt;br /&gt;
* limit access rights in time,&lt;br /&gt;
* avoid exposing user credentials to the client,&lt;br /&gt;
* support multi-factor authentication.&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which it could impersonate the resource owner. Instead of users having to completely trust the client, they can, and should, limit the privileges they grant the client to those needed for the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties,  &lt;br /&gt;
* the resource owner or user,  &lt;br /&gt;
* the user agent, e.g. the browser,  &lt;br /&gt;
* the client, e.g. a Single Page Application implemented in JavaScript and running in the browser,  &lt;br /&gt;
* the authorization server and  &lt;br /&gt;
* the resource server, or, in other words, the REST API.  &lt;br /&gt;
In the 4th grant type, resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
Neither in the Authorization Code nor in the Implicit Grant are client credentials handed to the client: when an access token is required, the client redirects the user agent to the authorization server. If the resulting interaction between resource owner and authorization server completes successfully, the user is redirected back to the client with a token which can be used to unlock access to resource servers. &lt;br /&gt;
&lt;br /&gt;
On the other hand, when the Resource Owner Password or Client Credentials Grant, resource owner credentials are exposed to the client. Hence it has been argued that these grant types do not afford better protection than Basic Authentication. Nonetheless, their use is a step in the right direction. &lt;br /&gt;
&lt;br /&gt;
In the past, OAuth has frequently been misused for authentication. With the increasingly widespread adoption and tool support for OpenID Connect, the temptation to do so has diminished. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is built on OAuth 2.0 and is widely used for authentication. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
Conventional wisdom says that authorization follows authentication - before granting permission, you need to know who is asking. OpenID Connect turns this on its head: it considers identity information as a resource and for the client to access it, the user, who is also the owner of these identity resources, must grant permission.&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233067</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233067"/>
				<updated>2017-09-10T05:00:50Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Basic Authentication does not provide a mechanism for logging the user out. Credentials are cached in the browser and re-submitted with subsequent requests. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant or secure design. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, authN/Z technologies should at least&lt;br /&gt;
* limit the scope of access rights granted to the client,&lt;br /&gt;
* limit access rights in time,&lt;br /&gt;
* avoid exposing user credentials to the client,&lt;br /&gt;
* support multi-factor authentication.&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which it could impersonate the resource owner. Instead of users having to completely trust the client, they can, and should, limit the privileges they grant the client to those needed for the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties,  &lt;br /&gt;
* the resource owner or user,  &lt;br /&gt;
* the user agent, e.g. the browser,  &lt;br /&gt;
* the client, e.g. a Single Page Application implemented in JavaScript and running in the browser,  &lt;br /&gt;
* the authorization server and  &lt;br /&gt;
* the resource server, or, in other words, the REST API.  &lt;br /&gt;
In the 4th grant type, resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
Neither in the Authorization Code nor in the Implicit Grant are client credentials handed to the client: when an access token is required, the client redirects the user agent to the authorization server. If the resulting interaction between resource owner and authorization server completes successfully, the user is redirected back to the client with a token which can be used to unlock access to resource servers. &lt;br /&gt;
&lt;br /&gt;
On the other hand, when the Resource Owner Password or Client Credentials Grant, resource owner credentials are exposed to the client. Hence it has been argued that these grant types do not afford better protection than Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233066</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233066"/>
				<updated>2017-09-10T04:35:44Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: Basic and Digest Authentication do not provide a mechanism for logging the user out.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Basic Authentication does not provide a mechanism for logging the user out. Credentials are cached in the browser and re-submitted with subsequent requests. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant or secure design. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, authN/Z technologies should at least&lt;br /&gt;
* limit the scope of access rights granted to the client,&lt;br /&gt;
* limit access rights in time,&lt;br /&gt;
* avoid exposing user credentials to the client,&lt;br /&gt;
* support multi-factor authentication.&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which it could impersonate the resource owner. Instead of users having to completely trust the client, they can, and should, limit the privileges they grant the client to those needed for the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short. OAuth 2.0 and OIDC's authorization server is an example of an STS.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233065</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233065"/>
				<updated>2017-09-10T04:06:16Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: also externalise the IdP. Use IdP and STS together.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant or secure design. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service and Identity Provider ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs in an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens.&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the identity token in OIDC. Access tokens, on the other hand, not necessarily.&lt;br /&gt;
&lt;br /&gt;
Arguments for externalising the STS also apply to the IdP. Moreover, upgrading to stronger authentication protocols becomes easier with authentication-mechanism agnostic API endpoints.&lt;br /&gt;
&lt;br /&gt;
IdPs can be used without STS, e.g. for validating Basic Authentication credentials, but this&lt;br /&gt;
* exposes credentials to the relying party&lt;br /&gt;
&lt;br /&gt;
* leads to higher coupling between service and authentication mechanism.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233056</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233056"/>
				<updated>2017-09-09T19:38:15Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs published by an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
Many STS implementations come bundled with an Identity Provider (IdP), but they are logically distinct:&lt;br /&gt;
* the IdP authenticates the user, or client,&lt;br /&gt;
* the STS issues tokens&lt;br /&gt;
Tokens may contain claims about the identity of the user, or client, as is the case for the Identity token in OIDC. Access tokens, on the other hand, do not necessarily contain identity claims.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233052</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233052"/>
				<updated>2017-09-09T19:23:11Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs published by an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but the downside is that functionality is duplicated, making it more difficult to ensure security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233049</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233049"/>
				<updated>2017-09-09T18:55:37Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs published by an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but this practice is questionable as functionality is duplicated, making it more difficult to ensure that security policies and patches are kept up to date and in sync across all endpoints. Key management also becomes more difficult.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233048</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233048"/>
				<updated>2017-09-09T18:52:40Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs published by an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
In principle, access control protocols could be implemented at each individual API endpoint. Some frameworks encourage this, but this practice is questionable as functionality is duplicated, making it more difficult to ensure that security policies and patches are kept up to date and in sync across all endpoints.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233047</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233047"/>
				<updated>2017-09-09T17:46:47Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: STS&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Externalising the Security Token Service ===&lt;br /&gt;
Modern access control protocols discussed in the previous section all rely on a security token being passed from client to server with a REST call. Clients obtain a security token from a Security Token Service, or STS for short.&lt;br /&gt;
&lt;br /&gt;
A single, centralised Security Token Service (STS) issuing access tokens for all APIs published by an organisation facilitates enforcing access control policies. The STS is a choke point through which all access requests must pass.&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233046</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233046"/>
				<updated>2017-09-09T13:29:07Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for authN/Z technologies that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233038</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233038"/>
				<updated>2017-09-08T16:55:14Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for technologies authN/Z that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. This is a departure from previous protocols where a client would receive user credentials with which they could impersonate the resource owner. Instead users having to completely trust the client, they can, and should, limit the privileges they grant the client to only cover the job at hand. This not only mitigates the risk of a malicious client somewhat, it also limits the impact of a client compromise. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233026</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233026"/>
				<updated>2017-09-08T10:04:44Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for technologies authN/Z that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Access tokens are issued by an authorization server. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner, the Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
The protocol in the first 3 grant types involves 5 parties, the resource owner or user, the user agent, e.g. the browser, the client, e.g. a Single Page Application implemented in JavaScript, the authorization server and the resource server, or, in other words, the REST API. In the 4th grant type, the resource owner and client coincide. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233025</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233025"/>
				<updated>2017-09-08T09:25:21Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
&lt;br /&gt;
==== Basic and Digest Authentication ====&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for technologies authN/Z that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. &lt;br /&gt;
&lt;br /&gt;
In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
==== OAuth 2.0 ====&lt;br /&gt;
The prime goal of [https://tools.ietf.org/html/rfc6749 OAuth 2.0] is to let users, in their capacity of resource owners, grant clients limited access to resources they control. Resources reside on resource servers which require an access token for access. Such access tokens are being issued by an authorization server. &lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 defines 3 ways in which the client can prove its entitlement to access a resource: &lt;br /&gt;
* Authorization Code Grant &lt;br /&gt;
* Implicit Grant &lt;br /&gt;
* Resource Owner Password Grant &lt;br /&gt;
It also defines a 4th grant type where the client is also the resource owner: Client Credentials Grant. &lt;br /&gt;
&lt;br /&gt;
==== OpenID Connect ====&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233023</id>
		<title>REST Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&amp;diff=233023"/>
				<updated>2017-09-08T07:24:00Z</updated>
		
		<summary type="html">&lt;p&gt;Yo: some of the criteria for assessing authN/Z protocols&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&lt;br /&gt;
= DRAFT MODE - WORK IN PROGRESS =&lt;br /&gt;
&lt;br /&gt;
== Introduction  ==&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] (or REpresentational State Transfer) is an architectural style first described in [https://en.wikipedia.org/wiki/Roy_Fielding Roy Fielding]'s Ph.D. dissertation on [https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm 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.&lt;br /&gt;
&lt;br /&gt;
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. The primary connector types are client and server, secondary connectors include cache, resolver and tunnel.&lt;br /&gt;
&lt;br /&gt;
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. 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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
== Access Control ==&lt;br /&gt;
&lt;br /&gt;
=== Protocols for Authentication and Authorization ===&lt;br /&gt;
Authentication has been in the HTTP spec since 1995 when the first draft of RFC 1945 was published. Initially, only Basic Authentication was standardized, later to be supplemented with Digest Authentication, e.g. in RFC 2069, in an attempt to mitigate the obvious insecurity of sending username and password in cleartext. Given that it relies on MD5 hashes, it is unclear that it affords much better security. Digest Authentication never gained a lot of traction, but Basic Authentication became very popular. HTTPS mitigates the most obvious security problems with Basic Authentication. &lt;br /&gt;
&lt;br /&gt;
While using Basic Authentication to control access to REST APIs seems straightforward, designers need to be aware of following limitations: &lt;br /&gt;
* In order to make a REST call on behalf of a user, the user must hand over credentials to the client. The client could, for example, be a mobile application. In effect, the client has been given unlimited scope to impersonate the user. In other words, the user has granted all access rights to all resources in the authentication realm forever, or at least until the password is changed. &lt;br /&gt;
* Each API endpoint must have access to the password database. Effectively, this means that all APIs are part of the attack surface. Since a password database is a high-value target, its attack surface should be carefully controlled. This becomes almost impossible as the number of endpoints grows and the API need to evolve quickly. &lt;br /&gt;
* Authentication and authorization logic runs on every endpoint. Ideally, this would be shared code, subjected to rigorous QA, but this may be difficult to realise as  distinct API endpoints may have different release cycles. Any security patch would impact all endpoints. &lt;br /&gt;
* Basic Authentication is inherently tied to passwords. While passwords are convenient and cheap, they are unsuitable as the sole  means of authenticating to gain access to high-value resources. Introducing a second factor to complement Basic Authentication is probably technically doable, but is unlikely to lead to an elegant design and would further exacerbate the difficulties of releasing and maintaining the purpose-build authentication library. &lt;br /&gt;
* Before users can make use of an API, they must be registered with the service. This is at odds with casual use. &lt;br /&gt;
Digest Authentication suffers from the same drawbacks.&lt;br /&gt;
&lt;br /&gt;
Basic and Digest Authentication are therefore not suitable authentication mechanisms except for the simplest, standalone, low-value REST API that provides services to a well-defined, stable community. For anything else, we look for technologies authN/Z that&lt;br /&gt;
* remove the responsibility for implementing the authentication protocol away from the endpoint,&lt;br /&gt;
* limits the scope of the access rights granted to the client,&lt;br /&gt;
* limits access permissions in time,&lt;br /&gt;
* avoids exposing user credentials to the client,&lt;br /&gt;
* interoperates with a variety of identity providers,&lt;br /&gt;
* supports multi-factor authentication,&lt;br /&gt;
to name but of a few. In the remainder of the section, modern protocols that address these concerns are reviewed.&lt;br /&gt;
&lt;br /&gt;
* OAuth 2.0  &lt;br /&gt;
The OAuth 2.0 authorization framework enables a application to obtain limited access to an HTTP service, either by resource owners granting an application access to the HTTP service on their behalf, or by allowing an application to obtain access on its own behalf. &lt;br /&gt;
&lt;br /&gt;
https://tools.ietf.org/html/rfc6749&lt;br /&gt;
&lt;br /&gt;
* OpenID Connect&lt;br /&gt;
The OpenID Connect standard is based on OAuth 2.0 and is widely used in authentication.  It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as obtain basic profile information in JSON Web Token format. &lt;br /&gt;
&lt;br /&gt;
https://openid.net/connect/&lt;br /&gt;
&lt;br /&gt;
=== Anti-farming ===&lt;br /&gt;
&lt;br /&gt;
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organisations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet.  &lt;br /&gt;
&lt;br /&gt;
API keys can be used for every API request. If there is any suspicious behavior in the API requests, the caller can be identified by the API Key and its key revoked. Furthermore, rate limiting is often also implemented based on API keys. Note, however, that API keys are susceptible to theft and should not be the sole defence mechanism on high-value targets. &lt;br /&gt;
&lt;br /&gt;
=== Protect HTTP methods ===&lt;br /&gt;
&lt;br /&gt;
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the caller is authorised to use the incoming HTTP method on the resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry. On the other hand, for the librarian, both of these are valid uses.&lt;br /&gt;
&lt;br /&gt;
=== Whitelist allowable methods ===&lt;br /&gt;
&lt;br /&gt;
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a &amp;lt;tt&amp;gt;GET&amp;lt;/tt&amp;gt; request might read the entity while &amp;lt;tt&amp;gt;PUT&amp;lt;/tt&amp;gt; would update an existing entity, &amp;lt;tt&amp;gt;POST&amp;lt;/tt&amp;gt; would create a new entity, and &amp;lt;tt&amp;gt;DELETE&amp;lt;/tt&amp;gt; would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs would work, while all others would return a proper response code (for example, a &amp;lt;tt&amp;gt;403 Forbidden&amp;lt;/tt&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In Java EE in particular, this can be difficult to implement properly. See [http://www.aspectsecurity.com/research-presentations/bypassing-vbaac-with-http-verb-tampering Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.&lt;br /&gt;
&lt;br /&gt;
=== Protect privileged actions and sensitive resource collections ===&lt;br /&gt;
&lt;br /&gt;
Not every user has a right to every web service. This is a vital point, as you don't want administrative web services to be misused:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/admin/exportAllData&lt;br /&gt;
&lt;br /&gt;
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.&lt;br /&gt;
&lt;br /&gt;
=== Protect against cross-site request forgery ===&lt;br /&gt;
&lt;br /&gt;
For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token-based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection.&lt;br /&gt;
&lt;br /&gt;
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].&lt;br /&gt;
&lt;br /&gt;
=== Insecure direct object references ===&lt;br /&gt;
&lt;br /&gt;
It may seem obvious, but if you had a bank account REST web service, you'd have to make sure there is adequate checking of primary and foreign keys:&lt;br /&gt;
&lt;br /&gt;
* https://example.com/account/325365436/transfer?amount=$100.00&amp;amp;toAccount=473846376&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to transfer money from any account to any other account, which is clearly absurd. Not even a random token makes this safe.&lt;br /&gt;
&lt;br /&gt;
* https://example.com/invoice/2362365&lt;br /&gt;
&lt;br /&gt;
In this case, it would be possible to get a copy of all invoices. &lt;br /&gt;
&lt;br /&gt;
This is essentially a data-contextual access control enforcement need. A URL or even a POSTed form should NEVER contain an access control &amp;quot;key&amp;quot; or similar that provides automatic verification. &amp;lt;b&amp;gt;A data contextual check needs to be done, server side, with each request.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== API Rate limits ===&lt;br /&gt;
The objective of the API Rate limits is to reduce massive API requests that cause denial of services, and also to mitigate potential brute-force attack, or misuses of the services. The API rate limits can be controlled at API gateway or WAF. The following API rate limits mechanism can be considered.&lt;br /&gt;
&lt;br /&gt;
* API rate limits per application or per API: Every API or application can only access the services for defined the number of requests per rate limit window. &lt;br /&gt;
* API rate limits per GET or POST request: The allowed access requests may vary based on GET or POST requests per period.&lt;br /&gt;
* HTTP error return code: If there are too many error return (i.e. 401, 404, 501...), the identifier of the API (API Key) will be blocked temporarily for further access.&lt;br /&gt;
&lt;br /&gt;
The results of exceeding API rate limits can be temporarily blacklisted the application/API access or notification alert to relevant users/admin. The service should return HTTP return code. &amp;quot;429 Too Many Requests&amp;quot; - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting.&lt;br /&gt;
== Input validation ==&lt;br /&gt;
&lt;br /&gt;
=== Input validation 101 ===&lt;br /&gt;
&lt;br /&gt;
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:&lt;br /&gt;
&lt;br /&gt;
* Assist the user &amp;gt; Reject input &amp;gt; Sanitize (filtering) &amp;gt; No input validation&lt;br /&gt;
&lt;br /&gt;
Assisting the user makes the most sense, as the most common scenario is &amp;quot;problem exists between keyboard and chair&amp;quot; (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to  sanitization or no input validation, make sure output encoding is very strong for your application. &lt;br /&gt;
&lt;br /&gt;
Log input validation failures, particularly if you assume that client-side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse.&lt;br /&gt;
&lt;br /&gt;
=== Secure parsing ===&lt;br /&gt;
&lt;br /&gt;
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 [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE] and similar attacks.&lt;br /&gt;
&lt;br /&gt;
=== Strong typing ===&lt;br /&gt;
&lt;br /&gt;
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. &lt;br /&gt;
&lt;br /&gt;
=== Validate incoming content-types ===&lt;br /&gt;
&lt;br /&gt;
When POSTing or PUTting new data, the client will specify the Content-Type (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response.&lt;br /&gt;
&lt;br /&gt;
=== Validate response types ===&lt;br /&gt;
&lt;br /&gt;
It is common for REST services to allow multiple response types (e.g. &amp;lt;tt&amp;gt;application/xml&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;application/json&amp;lt;/tt&amp;gt;, and the client specifies the preferred order of response types by the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header in the request. '''Do NOT''' simply copy the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header to the &amp;lt;tt&amp;gt;Content-type&amp;lt;/tt&amp;gt; header of the response. Reject the request (ideally with a &amp;lt;tt&amp;gt;406 Not Acceptable&amp;lt;/tt&amp;gt; response) if the &amp;lt;tt&amp;gt;Accept&amp;lt;/tt&amp;gt; header does not specifically contain one of the allowable types.&lt;br /&gt;
&lt;br /&gt;
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.&lt;br /&gt;
&lt;br /&gt;
=== XML input validation === &lt;br /&gt;
&lt;br /&gt;
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See  http://ws-attacks.org for examples of such attacks.&lt;br /&gt;
&lt;br /&gt;
=== Framework-Provided Validation ===&lt;br /&gt;
&lt;br /&gt;
Many frameworks, such as [https://jersey.java.net/ Jersey], allow for validation constraints to be enforced automatically by the framework at request or response time. (See [https://jersey.java.net/documentation/latest/bean-validation.html Bean Validation Support] for more information). While this does not validate the structure of JSON or XML data before being unmarshaled, it does provide automatic validation after unmarshaling, but before the data is presented to the application.&lt;br /&gt;
&lt;br /&gt;
== Output encoding ==&lt;br /&gt;
&lt;br /&gt;
=== Send security headers ===&lt;br /&gt;
&lt;br /&gt;
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an &amp;lt;tt&amp;gt;X-Content-Type-Options: nosniff&amp;lt;/tt&amp;gt; to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).&lt;br /&gt;
&lt;br /&gt;
Additionally the client should send an &amp;lt;tt&amp;gt;X-Frame-Options: deny&amp;lt;/tt&amp;gt; to protect against drag'n drop clickjacking attacks in older browsers.&lt;br /&gt;
&lt;br /&gt;
=== JSON encoding ===&lt;br /&gt;
&lt;br /&gt;
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser... or, if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user-supplied data properly to prevent the execution of user-supplied input on the browser.&lt;br /&gt;
&lt;br /&gt;
When inserting values into the browser DOM, strongly consider using &amp;lt;tt&amp;gt;.value&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.innerText&amp;lt;/tt&amp;gt;/&amp;lt;tt&amp;gt;.textContent&amp;lt;/tt&amp;gt; rather than &amp;lt;tt&amp;gt;.innerHTML&amp;lt;/tt&amp;gt; updates, as this protects against simple DOM XSS attacks. &lt;br /&gt;
&lt;br /&gt;
=== XML encoding ===&lt;br /&gt;
&lt;br /&gt;
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Cryptography ==&lt;br /&gt;
&lt;br /&gt;
=== Data in transit ===&lt;br /&gt;
&lt;br /&gt;
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.&lt;br /&gt;
&lt;br /&gt;
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.&lt;br /&gt;
&lt;br /&gt;
=== Data in storage ===&lt;br /&gt;
&lt;br /&gt;
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].&lt;br /&gt;
&lt;br /&gt;
== Message Integrity ==&lt;br /&gt;
In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can not only be used to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure the message integrity during the transmition.&lt;br /&gt;
&lt;br /&gt;
https://jwt.io/introduction/&lt;br /&gt;
&lt;br /&gt;
== Confidentiality ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/&amp;lt;id&amp;gt;/action]&lt;br /&gt;
* https://twitter.com/vanderaj/lists&lt;br /&gt;
&lt;br /&gt;
NOT OK:&lt;br /&gt;
&lt;br /&gt;
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (API Key in URL)&lt;br /&gt;
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/&amp;lt;id&amp;gt;/action?apiKey=a53f435643de32] (transaction not protected by TLS; API Key in URL)  &lt;br /&gt;
&lt;br /&gt;
== HTTP Return Code ==&lt;br /&gt;
HTTP defines status code [https://en.wikipedia.org/wiki/List_of_HTTP_status_codes].&lt;br /&gt;
When designing REST API, don't just use 200 for success or 404 for error.&lt;br /&gt;
&lt;br /&gt;
Here are some guideline to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks.   &lt;br /&gt;
&lt;br /&gt;
* 200 OK - Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. &lt;br /&gt;
* 201 Created - The request has been fulfilled and resource created. A URI for the created resource is returned in the Location header. &lt;br /&gt;
* 202 Accepted - The request has been accepted for processing, but processing is not yet complete. &lt;br /&gt;
&lt;br /&gt;
* 400 Bad Request - The request is malformed, such as message body format error.&lt;br /&gt;
&lt;br /&gt;
* 401 Unauthorized - Wrong or no authencation ID/password provided.&lt;br /&gt;
&lt;br /&gt;
* 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource&lt;br /&gt;
&lt;br /&gt;
* 404 Not Found - When a non-existent resource is requested&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting&lt;br /&gt;
&lt;br /&gt;
== Related articles ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and primary editors  =&lt;br /&gt;
&lt;br /&gt;
Erlend Oftedal - erlend.oftedal@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Andrew van der Stock - vanderaj@owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu Hsiang Chih- Hsiang_chihi@yahoo.com&amp;lt;br /&amp;gt;&lt;br /&gt;
Johan Peeters - yo@johanpeeters.com&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yo</name></author>	</entry>

	</feed>