Top 5 REST API Security Guidelines
Here is an annotated list of security guidelines for your REST APIs when you are developing and testing them, including proper authorization, input validation, and output encoding.
Join the DZone community and get the full member experience.Join For Free
when developing rest api, one must pay attention to security aspects from the beginning. in this post i will review and explain top 5 security guidelines when developing and testing rest apis .
rest (or representational state transfer) is a means of expressing specific entities in a system by url path elements. rest is not an architecture but it is an architectural style to build services on top of the web. rest allows interaction with a web-based system via simplified urls rather than complex request body or post parameters to request specific items from the system.
1/5 - authorization
protect http methods
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 incoming http method is valid for the session token/api key and associated resource collection, action, and record.
for example, if you have a 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.
whitelist allowable methods
it is common with restful services to allow multiple methods for a given url for different operations on that entity.
for example, a get request might read the entity while put would update an existing entity, post would create a new entity, and delete 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 403 forbidden ).
protect privileged actions and sensitive resource collections
not every user has a right to every web service. this is vital, as you don't want administrative web services to be misused:
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.
protect against cross-site request forgery
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.
csrf is easily achieved even using random tokens if any xss exists within your application, so please make sure you understand how to prevent xss.
more resources on csrf :
insecure direct object references
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:
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.
in this case, it would be possible to get a copy of all invoices.
this is essentially a data-contextual access control enforcement need. a url or even a posted form should never contain an access control "key" or similar that provides automatic verification. a data contextual check needs to be done, server side, with each request.
2/5 - input validation
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:
assist the user > reject input > sanitize (filtering) > no input validation
assisting the user makes the most sense, as the most common scenario is "problem exists between keyboard and chair" (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.
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.
consider rate limiting the api to a certain number of requests per hour or day to prevent abuse.
web applications/web services use input from http requests (and occasionally files) to determine how to respond.
attackers can tamper with any part of an http request, including the url, query string, headers, cookies, form fields, and hidden fields, to try to bypass the site’s security mechanisms.
common names for common input tampering attacks include forced browsing, command insertion, cross-site scripting, buffer overflows, format string attacks, sql injection, cookie poisoning, and hidden field manipulation.
use a secure parser for parsing the incoming messages. if you are using xml, make sure to use a parser that is not vulnerable to xxe and similar attacks.
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.
validate incoming content-types
when posting or putting new data, the client will specify the content-type (e.g. application/xml or application/json) 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 406 not acceptable response .
validate response types
it is common for rest services to allow multiple response types (e.g. application/xml or application/json, and the client specifies the preferred order of response types by the accept header in the request.
do not simply copy the accept header to the content-type header of the response. reject the request (ideally with a 406 not acceptable response) if the accept header does not specifically contain one of the allowable types.
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.
xml input validation
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.
3/5 - output encoding
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 x-content-type-options: nosniff to make sure the browser does not try to detect a different content-type than what is actually sent (can lead to xss).
additionally, the client should send an x-frame-options: deny to protect against drag'n drop clickjacking attacks in older browsers.
when inserting values into the browser dom, strongly consider using .value/.innertext/.textcontent rather than .innerhtml updates, as this protects against simple dom xss attacks.
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.
4/5 - cryptography
data in transit
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.
consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.
data in storage
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 owasp top 10 2010 - a7 insecure cryptographic storage.
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 transmission. for more information, you can visit https://jwt.io/introduction/ .
5/5 - http status codes
http defines status code. when design rest api, don't just use 200 for success or 404 for error.
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.
you will also find more information in this rest api error codes 101 blog post.
- 200 ok - response to a successful rest api action. the http method can be get, post, put, patch or delete.
- 400 bad request - the request is malformed, such as message body format error.
- 401 unauthorized - wrong or no authentication id/password provided.
- 403 forbidden - it's used when the authentication succeeded but authenticated user doesn't have permission to the request resource.
- 404 not found - when a non-existent resource is requested.
- 405 method not allowed - the error checking for unexpected http method. for example, the restapi is expecting http get, but http put is used.
- 429 too many requests - the error is used when there may be dos attack detected or the request is rejected due to rate limiting
401 vs 403
401 “unauthorized” really means unauthenticated, “you need valid credentials for me to respond to this request”.
403 “forbidden” really means unauthorized, “i understood your credentials, but so sorry, you’re not allowed!”
in this post, i have covered the top 5 restful api security issues and guidelines on how to address them. following these guidelines will result in a more secure and quality rest api service and a more developer-friendly rest api.
some methods (for example, head, get, options and trace) are defined as safe, which means they are intended only for information retrieval and should not change the state of the server.
when designing and building rest apis you have to pay attention to security aspects.
Published at DZone with permission of Guy Levin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.