10 Essential Tips for Writing Secure REST API

REST APIs are used to access and manipulate data using a common set of stateless operations. Let’s make them robust

admin

29. April 2021

Application programming interfaces (APIs) are everywhere. Most modern web applications expose APIs that clients can use to interact with the application.

They enable software to communicate with other pieces of software — internal or external — consistently, which is a key ingredient in scalability, not to mention reusability.

Like any technology, REST APIs bring their own unique security challenges. The question that remains is how to reduce those vulnerabilities.

Today we will discuss the following topics:

  1. What is REST API?
  2. Importance of REST API and application security
  3. Describe the top 10 best practices to secure REST APIs

If you want to secure the Spring boot Rest API using Spring Security, JWT, and JPA, there are many ways to do that.

What is a RESTful API?

  • An application programming interface (API) is a set of clearly defined methods of communication between various software components.
  • REST APIs are used to access and manipulate data using a common set of stateless operations.
  • These operations are integral to the HTTP protocol and represent essential create, read, update, and delete (CRUD) functionality, although not in a clean one-to-one manner
  • It’s more of an approach to design and communication than a single tool or programming library.
  • RESTful programming is stateless and provides a uniform interface, commonly using HTTP-based URLs with query parameters that mask the backend infrastructure from the user.
  • Responses typically come back as simple JSON-based key/value pairs, but APIs can support any type of content, including XML, test documents, or even images. Frontend software can then serve that data up in a format appropriate for the user.
  • A good API makes it easier to develop a computer program by providing all the building blocks.
  • REST APIs are the glue that holds the modern cloud-based software economy together. They can serve straightforward information, even from a large data set.
  • Your software can query Amazon’s API to get product pricing, for example, or get a geographic location from Google Maps.
  • Alternatively, it can query a complex backend service requiring lots of computing power. You want a service to tag a photograph with descriptive words or recognize someone’s face? Microsoft’s REST-based API does that.

Importance of API and Application Security

  • Businesses uses APIs to connect services and to transfer data, and so a hacked API can lead to a data breach.
  • Broken, exposed, or hacked APIs are behind major data breaches. They expose sensitive medical, financial, and personal data for public consumption.
  • That said, not all data is the same nor should be protected in the same way. How you approach API security will depend on what kind of data is being transferred.
  • Multiple types of data can be transferred via different APIs. Any implementation of API security needs to be specific to your APIs and the data being transferred.
  • API Injections are attacks in which the hacker injects malicious code into vulnerable software programs. The most common ones are SQL, NoSQL, and Command Injection.
  • A command or a query that contains untrusted data gets sent to an interpreter. The interpreter gets tricked into executing an unintended command or access data without valid authorization.
  • Try avoiding accessing external interpreters. That’s the simplest way of preventing API injection.
  • Make sure your web application only runs using the needed privileges for its functions. That way a hacker can’t exploit administrative privileges that the web application has.
  • You need to ensure that your application endpoints (the URLs used to access the interface) are not vulnerable to attacks that get through the interface or bypass it.

Best Practices of Secure REST APIs

Rock-solid authentication and authorization mechanisms are the beginning for REST API security, but not the end. There are other security best practices to consider during development.

By using signatures, encryption, quotas, throttling, tokens, API gateways, etc., your API security increases immensely.

1. Always use HTTPS

Always use TLS and a security framework that’s well-established and has a large community behind it.

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.

By always using SSL, the authentication credentials can be simplified to a randomly generated access token. The token is delivered in the username field of HTTP Basic Auth. It’s relatively simple to use, and you get a lot of security features for free.

2. Ensure proper 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.

You can implement generic filters where all authentication and authorization may ensure. before accessing non-public API, you must ensure is requester has enough permission/grant to access this API.

3. Consider JWT and OAUTH combined

For authentication purpose, you can use JSON Web Token (JWT), and for authorization, you can use OAuth2.

REST APIs also use JavaScript Object Notation (JSON), which is a file format that makes it easier to transfer data over web browsers and API. By using HTTP and JSON, REST APIs don’t need to store or repackage data, making them much faster than SOAP APIs.

Though basic auth is good enough for most of the APIs, if implemented correctly, it’s secure as well — yet you may want to consider OAuth as well.

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its behalf.

4. Input parameter validation

Validate request parameters on the very first step, before it reaches application logic. Validate parameter-based inputs for queries. Put strong validation checks and reject the request immediately if validation fails.

Attackers can change URL parameters, JSON request data, and XML input. Fuzzers can pummel REST APIs with subtle input changes, so be diligent here.

  • Do not trust input parameters/objects.
  • Validate input, such as 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 regex.
  • Reject unexpected and/or illegal content.
  • Make use of validation and/or 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.

5. Whitelisting permitted HTTP methods

Provide another layer of defense by whitelisting permitted HTTP methods (e.g., GET, POST, and PUT). Block by default those that you might never want someone to access via a public API (e.g., DELETE).

Similarly, authenticate individual users for specific actions. You might allow external users a single query, but not the ability to export all data, for example.

  • 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

6. Use whitelisted IPs if possible

For a server to server communication, you can use whitelisted IPs. If the requester IP belongs to your whitelisted IP list then you may allow them.

If your API consumer is mobile apps, then this process is not possible because they don’t have permanent IP addresses.

7. Use quotas and throttling

Place quotas on how often your API can be called and track its use over history. More calls on an API may indicate that it is being abused. It could also be a programming mistake, such as calling the API in an endless loop. Make rules for throttling to protect your APIs from spikes and Denial-of-Service attacks.

8. Log all failed request and analyze using tools

You may log all failed requests and look for patterns to identify sustained attacks. Also, send relevant error messages with appropriate HTTP status codes to help developers connecting to your service.

Analyze the failed logs periodically by log analyzer, and for serious errors like access forbidden, make sure they send an email or SMS for admin or relevant persons.

9. Use an API gateway

API gateways act as the major point of enforcement for API traffic. A good gateway will allow you to authenticate traffic as well as control and analyze how your APIs are used.

10. Keep it Simple

Secure an API/System just how secure it needs to be. Every time you make the solution unnecessarily complex, you are also likely to leave a hole.

Conclusion

Thanks for reading this article. Hope you enjoy this.

If you want to learn Microservice implementation using spring cloud with docker, this article can help.