REST is widely used architectural style for designing networked applications. It is used to build scalable and maintainable web services. REST stands for Representational State Transfer. It uses HTTP methods like GET, POST, PUT, and DELETE to manipulate the resources. RESTful web services are stateless, which means each request is independent of the previous one. This makes REST a suitable choice for stateless microservices. RESTful APIs are easy to develop, test, deploy, and consume. Its popularity has been increasing with the emergence of cloud computing and microservices.
In this article, we shall go through some key security considerations when designing RESTful APIs. Security is paramount in any web application that processes sensitive data. Here are some key security considerations to keep in mind when designing RESTful APIs:
Introduction
The key abstraction of information in REST is a resource. A REST API resource is identified by a URI, usually an 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 transfer that representation.
The primary connector types are client and server, secondary connectors include cache, resolver, and tunnel.
REST APIs are stateless. Stateful APIs do not adhere to the REST architectural style. State in the REST acronym refers to the state of the resource which the API accesses, not the state of a session within which the API is called. While there may be good reasons for building a stateful API, it is important to realize that managing sessions is complex and difficult to do securely.
Anti-Pattern: Passing state from client to backend, while making the service technically stateless, is an anti-pattern that should be avoided as it is prone to replay and impersonation attacks.
In order to implement flows with REST APIs, resources are typically created, read, updated, and deleted.
For Example: an e-commerce 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.
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.
HTTPS
Secure REST services must only provide HTTPS endpoints. This protects authentication credentials in transit, for example, passwords, API keys, or JSON Web Tokens. It also allows clients to authenticate the service and guarantees the integrity of the transmitted data.
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.
Access Control
Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorization logic, and session management. This has several drawbacks for modern architectures which compose multiple microservices following the RESTful style.
In order to minimize latency and reduce coupling between services, the access control decision should be taken locally by REST endpoints
User authentication should be centralized in an Identity Provider (IdP), which issues access tokens
JWT
There seems to be a convergence towards using JSON Web Tokens (JWT) as the format for security tokens. JWTs are JSON data structures containing a set of claims that can be used for access control decisions. A cryptographic signature or message authentication code (MAC) can be used to protect the integrity of the JWT.
Ensure JWTs are integrity protected by either a signature or a MAC. Do not allow the unsecured JWTs: {"alg":"none"}.
In general, signatures should be preferred over MACs for the integrity protection of JWTs.
API Keys
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 organizations to monetize APIs; instead of blocking high-frequency calls, clients are given access in accordance with a purchased access plan.
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.
Require API keys for every request to the protected endpoint.
Return 429 Too Many Requests HTTP response code if requests are coming in too quickly.
Revoke the API key if the client violates the usage agreement.
Do not rely exclusively on API keys to protect sensitive, critical, or high-value resources.
Restrict HTTP methods
Apply an allowed list of permitted HTTP Methods e.g. GET, POST, PUT.
Reject all requests not matching the allow list with HTTP response code 405 Method not allowed.
Make sure the caller is authorized to use the incoming HTTP method on the resource collection, action, and record
Input validation
Do not trust input parameters/objects.
Validate input: length/range/format and type.
Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters.
Constrain string inputs with regexp.
Reject unexpected/illegal content.
Make use of validation/sanitation libraries or frameworks in your specific language.
Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large.
Consider logging input validation failures. Assume that someone who is performing hundreds of failed input validations per second is up to no good.
Use a secure parser for parsing incoming messages. If you are using XML, make sure to use a parser that is not vulnerable to XXE and similar attacks.
Validate content types
A REST request or response body should match the intended content type in the header. Otherwise, this could cause misinterpretation on the consumer/producer side and lead to code injection/execution.
Document all supported content types in your API.
Error handling
Respond with generic error messages - avoid revealing details of the failure unnecessarily.
Do not pass technical details (e.g., call stacks or other internal hints) to the client.
Audit logs
Write audit logs before and after security-related events.
Consider logging token validation errors in order to detect attacks.
Take care of log injection attacks by sanitizing log data beforehand.
CORS
Cross-Origin Resource Sharing (CORS) is a W3C standard to flexibly specify what cross-domain requests are permitted. By delivering appropriate CORS Headers your REST API signals to the browser which domains, AKA origins, are allowed to make JavaScript calls to the REST service.
Disable CORS headers if cross-domain calls are not supported/expected.
Be as specific as possible and as general as necessary when setting the origins of cross- domain calls.
Sensitive information in HTTP requests
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.
In POST/PUT requests sensitive data should be transferred to the request body or request headers.
In GET requests sensitive data should be transferred in an HTTP Header.
OK:
https://example.com/resourceCollection/[ID]/action
NOT OK:
https://example.com/controller/123/action?apiKey=a53f435643de32
because API Key is into the URL.
Comments