Implementing a new application programming interface (API) for your online application is an exciting step. It’s great for third-party developers looking to integrate with your app, great for customers who benefit from your app’s integrations, and great for your profits as you draw more users to your platform.

Unfortunately, new APIs are also great news for hackers, as they provide another means to exploit information stored on your servers. 

In this post, we’ll explain the fundamentals of API security, including common threats against APIs and the best ways to defend against them, so you can reap the benefits of this technology without the downfalls.

Download Now: Free Intro Guide to HTML & CSS

The goal of APIs is to facilitate the transfer of data, often private, between your system and external users. Therefore, a poorly maintained and insecure API is an unlocked gate to your sensitive data.

If this comes off as alarmist, know that billions of records have been exposed from cyberattacks, many due to insecure APIs:

a line graph of API breaches over time

Image Source

Successful API hacks have affected businesses including Facebook, Venmo, Twitter, and even the United States Postal Service. To stay off this list and protect your sensitive data, you’ll need to integrate API security principles into your planning and build process. 

Why API Security Is Important

While cybersecurity is a broad topic that encompasses all online technologies, APIs present unique challenges because they sit between third-party developers and a company’s resources. Successful API security breaches can be especially harmful to an application and its users, since a hacked endpoint grants direct access to sensitive information.

It’s hard to overstate the potential effect of a successful attack. While the financial impact can be substantial, the damage to your brand may be irreparable. You’ll surely lose customer trust, as well as credibility with companies using your API. Third-party integrated apps may even be harmed by extension.

Types of API Cyberattacks

Before we review the best practices to harden your API, we need to know what we’re up against. Here are the most common attacks against APIs that you should know:

Stolen Authentication

One of the simplest ways to access an API is to hijack the identity of an authorized user. For example, if an authentication token falls into the wrong hands, it can be used to access resources with malicious intent while appearing legitimate. Cybercriminals will also try to guess authentication passwords or break a weak authentication process to gain access.

Man-in-the-Middle Attack

A man-in-the-middle (MITM) attack occurs when a hacker intercepts an API request or response between an end-user and an API. They may steal the sensitive contents of this communication (e.g. account login credentials or payment information) or modify the contents of the request/response.

Code Injections

APIs with gaps in authentication and validation are also vulnerable to code injections, in which an attacker sends a script to an application’s server via an API request. This script is intended to expose or delete data, plant false information, and/or harm the application’s internals. You’ll also see the term “SQL injection” used — this is a code injection performed on a SQL database.

Denial-of-Service Attack

Denial-of-service (DoS) attacks overwhelm a server’s resources with API requests to slow, break, or crash the web server. Often, these attacks are made from multiple malicious sources simultaneously — a distributed denial-of-service (DDoS) attack.

Despite these risks, APIs aren’t going away any time soon. Virtually any online application seeking to integrate with others will need one or APIs in place, and every new web API presents another opportunity for hackers to exploit personal data. Therefore, anyone overseeing a software integration should understand proper API-specific security measures.

While any organization with an API can be targeted, each will implement APIs — and API security — differently. An API that provides access to payment information requires more precautions than, say, an image-sharing service.

This is why the following tips are general and apply to any application implementing a REST API. REST APIs transfer data via the Hypertext Transfer Protocol (HTTP), the same method used to send HTML documents to browsers (which we see as websites). This type of architecture is used by many public APIs and internal APIs (used in microservices, for example). Netflix, Uber, and Trello are just a few modern apps that use REST APIs. 

By following the guidelines below, you’ll greatly reduce the risks associated with maintaining an API, no matter your niche.

1. Implement authentication.

Before processing a request, an API performs authentication — it needs to verify the identity of the user or program that sent the request.

Typically, APIs authenticate with a password, multi-factor authentication, and/or an authentication token, which is a string of characters that serves as a unique identifier for a user. To authenticate a request with a token, an API matches the token sent in the request with one stored in its database. Tokens help an organization keep track of those trusted with its resources.

Today, the OAuth protocol is the widely accepted standard for API user authentication. OAuth was originally designed for social login, allowing users to log into third-party applications with passwords without revealing their passwords. For example, OAuth lets me use my Google password to sign into a third-party website like LinkedIn, without requiring LinkedIn to store my password.

OAuth is built on HTTP, which also makes it a great fit for REST APIs. While the inner-workings of OAuth are beyond the scope of this article, on a basic level OAuth gives API administrators a way to grant authentication tokens to approved third parties. Admins can set custom access rules that determine which API requests are permitted, based on the source of the request.

2. Implement authorization.

After verifying the identity of the user sending the request, an API needs a way to grant access to only the authorized resources and methods. For example, a user might be approved to access the API, but if they’re not allowed to add information to the application’s database via the POST method, any request to do so should be rejected. Authorization information can also be contained within a request as a token.

Unlike some other API types, REST APIs must authenticate and authorize each request made to the server, even if multiple requests come from the same user. This is because REST communications are stateless — that is, each request can be understood by the API in isolation, without information from previous requests.

Authorization can be governed by user roles, where each role comes with different permissions. Generally, API developers should adhere to the principle of least privilege, which states that users should only have access to the resources and methods necessary for their role, and nothing more. Predefined roles make it easier to oversee and change user permissions, reducing the chance that a bad actor can access sensitive data.

3. Validate all requests.

As mentioned, sometimes requests from perfectly valid sources may be hacking attempts. Therefore, APIs need rules to determine whether a request is friendly, friendly but invalid, or harmful, like an attempt to inject harmful code.

An API request is only processed once its contents pass a thorough validation check — otherwise, the request should never reach the application data layer.

4. Encrypt all requests and responses.

To prevent MITM attacks, any data transfer from the user to the API server or vice versa must be properly encrypted. This way, any intercepted requests or responses are useless to the intruder without the right decryption method.

Since REST APIs use HTTP, encryption can be achieved by using the Transport Layer Security (TLS) protocol or its previous iteration, the Secure Sockets Layer (SSL) protocol. These protocols supply the S in “HTTPS” (“S” meaning “secure'') and are the standard for encrypting web pages and REST API communications.

TLS/SSL only encrypts data when that data is being transferred. It doesn’t encrypt data sitting behind your API, which is why sensitive data should also be encrypted in the database layer as well.

5. Only include necessary information in responses.

Like you might unintentionally let a secret slip when telling a story to a friend, it’s possible for an API response to expose information hackers can use. To prevent this, all responses sent to the end-user should include only the information to communicate the success or failure of the request, the resource requested (if any), and any other information directly related to these resources.

In other words, avoid “oversharing” data — the response is a chance for you to inadvertently expose private data, either through the returned resources or verbose status messages.

6. Throttle API requests and establish quotas.

To prevent brute-force attacks like DDoS, an API can impose rate-limiting, a way to control the number of requests to the API server at any given time.

There are two main ways to rate-limit API requests, quotas and throttling. Quotas limit the number of requests allowed from a user over a span of time, while throttling slows a user’s connection while still allowing them to use your API.

Both methods should allow normal API requests but prevent floods of traffic intended to disrupt, as well as unexpected request spikes in general.

7. Log API activity.

Up to this point, we’ve covered preemptive methods for countering API threats. However, in the case of a successful hack on your system, you’ll want a way to trace the source of the incident so you can remedy and report the problem.

This is why logging all API activity is essential — if attackers breach your protections, you can assess what they did and how they got in. If nothing else, you can use an attack to further harden your API, potentially preventing similar incidents in the future.

8. Conduct security tests.

Don’t wait until an actual attack to see how your safeguards hold up. Instead, leave ample time for security testing, in which you intentionally hack your API to expose vulnerabilities. Remember: testing isn’t a one-and-done process — it should be performed on a routine basis, especially when your API is updated.

Let's take a closer look at this step below. 

API Security Testing

The first step of API security is ensuring that your API is working as expected. That means submitting normal requests via an API Client and making sure they stick to the principles above. Develop scenarios that answer the following:

  • Can only authenticated users access your endpoints?
  • Are users granted access to only the necessary endpoints based on their roles?
  • Is the correct information returned in responses for each potential request?
  • Are benign but invalid requests rejected?

Once you've established that your API is working normally, you’ll need to simulate code injection, MITM, DoS, and stolen password attacks against your systems in a proper testing environment. Address the following in your tests:

  • Can my authentication counter brute-force entry attempts?
  • How does my API handle significant spikes in requests?
  • What if an authenticated user submits a harmful script or file via a request?
  • Are all data transfers encrypted? Are requests without TLS/SSL (i.e. with HTTP and not HTTPS) prohibited?
  • What if a request or response is intercepted? How will my API and the user know?

Below are some specific tests you can run. 

API security testing

User Authentication Test

If authentication mechanisms are implemented incorrectly, attackers can compromise authentication tokens or exploit implementation flaws to assume other users’ identities and gain access to your API’s endpoints.

To test your authentication mechanisms, try sending API requests without proper authentication (either no tokens or credentials, or incorrect ones) and see if your API responds with the correct error and messaging. 

Parameter Tampering Test

To run a parameter tampering test, try various combinations of invalid query parameters in your API requests and see if it responds with the correct error codes. If not, then your API likely has some backend validation errors that need to be resolved.

Injection Test

To test if your API is vulnerable to injections, try injecting SQL, NoSQL, LDAP, OS, or other commands in API inputs and see if your API executes them. These commands should be harmless, like reboot commands or cat commands. 

Unhandled HTTP Methods Test

Most APIs have various HTTP methods that are used to retrieve, store, or delete data. Sometimes web servers will give access to unsupported HTTP methods by default, which makes your API vulnerable.

To test for this vulnerability, you should try all the common HTTP methods (POST, GET, PUT, PATCH, and DELETE) as well as a few uncommon ones. TRY sending an API request with the HEAD verb instead of GET, for example, or a request with an arbitrary method like FOO. You should get an error code, but if you get a 200 OK response, then your API has a vulnerability. 

Fuzz Test

Fuzz testing should be one of the last steps of your API security auditing process. This type of testing requires your API to be pushed to its limits in order to discover any functional or security issues that have yet to be revealed.

To achieve this, send a large number of randomized requests, including SQL queries, system commands, arbitrary numbers, and other non-text characters, and see if your API responds with errors, processes any of these inputs incorrectly, or crashes. This type of testing will mimic Overflow and DDoS attacks.

An API manager or gateway tool will handle or help address the API security guidelines described above (including testing). Let's take a closer look at these tools below.

Arguably, the most important function of API management platforms is access control. They should prevent unauthorized users from gaining inappropriate levels of access to your API’s services and data.

To enforce access control, most API management platforms support at least one or all three types of security schemes outlined below:

  • API key: A single token string that provides unique authentication information.
  • Basic Authentication: A two token string solution, like a username and password, that provides unique authentication information. 
  • OpenID Connect (OIDC): A simple identity layer on top of the OAuth framework, which verifies users by obtaining basic profile information, for example, and using an authentication server.

To discover some popular API management platforms that can help you secure your APIs, check out What Is an API Gateway & How Does It Work? [+Best Service Providers].

The focus of this post has been on REST APIs since they are the most common type, but any API is at risk for security breaches. That's why we'll go over the key differences between REST API security and the security of another common API type: SOAP. 

REST API Security vs SOAP API Security

Software developers may follow different architectures to build an API. The most popular are Representational State Transfer (REST) and Simple Object Access Protocol (SOAP). 

While REST APIs transfer data via the Hypertext Transfer Protocol (HTTP), SOAP encodes data in XML — a common markup language for storing and transferring information — and sends it via HTTP.

SOAP is more strict in its requirements than RESTful design, which makes this type of API more difficult to build. However, it also tends to be more secure and better at preserving data integrity than other API designs as a result.

Let’s break down their differences below. 

RESTful API Security

The RESTful protocol supports SSL to protect data when being transferred, but it lacks built-in security capabilities, including error handling. It also does not support the Web Services (WS) specifications so you can’t use security extensions like Web Services Security for enterprise-grade security.

That means the security of REST API's depends on the design of the API itself or an API gateway.

The graphic below provides a quick summary of RESTful API security:

RESTful API Security

SOAP API security

Like RESTful, the SOAP protocol also supports SSL to protect data when being transferred but it goes further. Not only does it include SAML tokens, XML encryption, and XML signatures (based on W3C and OASIS recommendations), which help secure the data being sent and received by SOAP APIs — it also supports the Web Services (WS) specifications.

This lets you use security extensions like Web Services Security for enterprise-grade security and WS-ReliableMessaging, which provides built-in error handling.

The graphic below provides a quick summary of SOAP API security:

SOAP API Security

Protect Your Users By Protecting Your API

It’s easy to get bogged down in the jargon when it comes to APIs and security. However, remember that at the root of this work is a duty to protect your users — this extends to those who entrust you with their data, plus developers utilizing your API.

API technology brings a myriad of possibilities to online applications, but a security incident can quickly eclipse any benefits you get from an API. While it’s impossible to eradicate all threats, the principles above are necessary for any organization that cares about its reputation and, more importantly, its customers.

Editor's note: This post was originally published in December 2020 and has been updated for comprehensiveness.

New Call-to-action

 css introduction

Originally published Sep 24, 2021 7:00:00 AM, updated September 24 2021

Topics:

Application Programming Interface (API)