11 Incredibly Effective API Security Best Practices

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)

41% of organizations were victims of an API attack in the last 12 months. Don’t take your API security for granted ever again. Follow our top 11 best practices and learn how to protect your users’ and organization’s sensitive data by boosting your API’s defenses

Is your organization using application programming interfaces (APIs)? You’re not alone. In every industry, more and more applications and systems are communicating through APIs. They’re so popular that in the first week of December 2021, API calls represented 54% of Cloudflare’s global network traffic.

Why are APIs so popular? Because they’re great when designed well. They’re efficient, extremely user-friendly, and easy to integrate and customize. These interfaces enable developers to automate repetitive tasks in a breeze. While all of this is good, there’s still a catch: API attacks are exploding. Over the last year, Salt Security observed a 117% increase in malicious API traffic compared to the previous year.

Do you want to reap the benefits of APIs while keeping your organization and customers’ data secure? Discover our top 11 API security best practices. Learn how to prevent security threats and secure your API now.

Know Your API Security Risks

Have you ever wondered how you can check the weather on your smartphone or send a message through your Facebook app? It’s all thanks to the magic work of an API. How? Let’s say you want to check tomorrow’s weather using your favorite mobile app. The app connects to the internet and, through an API, sends the request to a server (endpoint). Once the server has found, the data in the database sends the information back through the network in a way that’s easily read by humans.

Nice, fast, and easy. But is it also secure? Not always. Or, at least, it isn’t if you, as a developer, haven’t taken certain precautions (i.e., followed API security best practices) during the whole secure software development life cycle (SSDLC).

Don’t forget that APIs are designed to give virtually anyone access to data. Hackers know that. T-Mobile had a taste of it in 2018. And with 48 API-related new vulnerabilities identified in Q1 2022 alone, can you imagine what could happen to your money if a cybercriminal could exploit one of those flaws? It’s easier than you think, and bad guys have plenty of attack methods to choose from.

Code Injection Attacks

An attacker inserts malicious code through an API request and gets access to sensitive data stored in the database, such as passwords and usernames. An example of this type of attack is an SQL injection, as illustrated in the following graphic:

sql injection example

This is how an attacker could get hold of all your organization’s IDs and passwords using an SQL injection.

Man-In-the-Middle Attacks (MITMs)

A hacker intercepts your online banking API request to transfer some money to your friend’s bank account. Once done, they pose as you and replace your friend’s bank account number with their own. The money is gone and you’re left taking the blame.

man in the middle attack example

This graphic shows how an attacker can trick you into transferring money to his bank account without you knowing it using a man-in-the-middle attack.

Cross-Site Scripting Attacks (XSS)

The attacker injects your online banking website with a malicious script. You go on it, try to log in and the script sends your password and username to the attacker.

cross site scripting attack example

The graphic shows an example of an XSS attack.

Credential Stuffing and Brute Force Attacks

A cybercriminal uses a list of common passwords and usernames (or stolen credentials in case of credential stuffing) to gain access to the API authentication endpoint (more on that later). If there’s also your password and user ID among that data, it’s a jackpot. He gets access to your bank account.

credential stuffing attack example

The graphic shows how an attacker can get access to your bank account through credential stuffing.

And these are just a few of the most common attack techniques. The responsibility of keeping your API secure has become so important that OWASP created a dedicated top 10 vulnerabilities list. Can’t be bothered to go through the whole thing? Check out this OWASP API Security top 10 webinar.

Does this have given you a better picture of what you’re up against? OK, now it’s time to explore our top 11 API security best practices that’ll help you protect your APIs from the bad guys.

11 API Security Best Practices

As we’ve just seen, APIs can present some significant challenges when talking about security. Here, are our essential API security best practices that can help you keep your sensitive data and customers safe.

Too busy developing and securing your API? No problem at all. Check out our summary table below to get the top highlights for the listed API security best practices:

API Security Best Practices Examples
1. Implement Security From the Very Beginning
  • Replace your traditional software development life cycle (SDLC) process.
  • Pick a secure software development framework (SSDF).
  • Build threat models.
  • Set the correct security policies and configurations.
2. Stay Up to Date With the Latest Vulnerabilities
  • Subscribe to security newsletters.
  • Check security news portals and blogs.
  • Don’t miss API-specific reports.
3. Enable Encryption to Secure Your Traffic
  • Use transport layer security (TLS) with a web certificate.
4. Implement Strong Authentication Methods
  • HTTPS-based authentication.
  • API key authentication.
  • OAuth and OpenID Connect Authentication.
5. Manage and Store Your Keys Securely
  • Use an API secret management service.
  • Generate new keys periodically.
  • Avoid storing your keys on the client side.
  • Restrict your API key usage.
6. Limit the Information You Share
  • Limit the information displayed by error messages.
  • Use blacklists (blocklists) and whitelists (allowlists).
  • Remove sensitive information before publishing your API.
  • Use scanning tools.
7. Validate All Inputs
  • Use JSON or XML schema validation.
  • Implement semantic and syntax validation.
  • Test your API.
8. Implement Rate Limits Using Quotas or Throttling
  • Throttle API requests.
  • Apply quotas (restrictions) to prevent overloads.
9. Use Firewalls to Secure Your Network

Configure your firewalls in the:

  • Demilitarized zone (DMZ) network layer.
  • Local area network (LAN) layer.
10. Log and Monitor Users Activities

There are many API monitoring tools available on the market. Among them, popular tools include:

  • Loggly.
  • Manage Engine Application Manager.
  • AlertSite.
11. Embrace a Zero-Trust Model

No one is trusted inside or outside the organization’s network, even once they’ve been

  • Authenticated,
  • Authorized, and
  • Constantly monitored.

1. Implement Security From the Very Beginning

In other words, don’t wait until the horse is gone to close your barn door. The security of your API shouldn’t be an afterthought, it should be the first thing to consider when developing an API. OK, I can already hear you saying: “Can’t do that. My boss is constantly on my back pushing for faster releases, I have no time for security.”

We get it — we’ve all been there and experienced the same issues. But the good news is that we have found the solution:

  • Replace your traditional software development life cycle process (SDLC). Modern APIs demand modern development processes. Replace the old SDLC model with the secure software development life cycle (secure SSDLC or SSDLC), where security is embedded into each phase of the development process right from the start.

secure software development life cycle

The graphic shows an example of the SSDLC life cycle.

  • Bake security into your SDLC. Does this sound too complicated and you don’t know where to start? Don’t scratch your head. Pick a secure secure software development framework (SSDF) and follow its suggestions to address security vulnerabilities and threats throughout each step of your SDLC.
  • Build threat models. As the adage goes, “The early bird catches the worm.” Threat models will enable you to identify and fix potential issues early in the software development process. This will enable you to reduce the number of threats from the beginning and avoid making costly changes down the line. There are many methodologies available. Among them:
  • Trike. This open-source threat model methodology is available as a spreadsheet or standalone tool.
  • OWASP Threat Dragon. This is another open-source web-based tool that lets you create potential threat lists.
  • Set the correct security policies and configurations. Ensuring to apply the right configuration and security policies is key to the security of your API. These policies and specific configurations will enable you to define who has access to the API, how they can access it (for example, using OAuth), and set rate limits. We’ll talk more about it in a minute, as we’ve included some examples further down our API security best practices list.

2. Stay Up to Date With the Latest Vulnerabilities

When was the last time you checked the list of vulnerabilities recorded by the National Institute of Standards and Technology (NIST) on the Cybersecurity and Infrastructure Security Agency (CISA)’s website? The number of API-specific vulnerabilities reported in Q2 2022 increased by an astonishing 268% compared to Q1 2022. Isn’t it time to ensure you’re up to date with the latest security flaws and API hacking techniques used by hackers? How?

  • Subscribe to security newsletters. Websites like CISA offer several free subscriptions to mailing lists and RSS feeds.
  • Check security news portals and blogs. Would you rather check a website than get your inbox flooded by alerts and newsletters? I don’t blame you. The good news is that the internet is full of resources and articles waiting for hungry readers. There are even API security-specific blogs like APISecurity.io.
  • Don’t miss API-specific reports. Every year, many organizations in the industry publish free reports on various topics, including API-related ones. OWASP is also working on a new updated version of its API vulnerabilities top 10 list. Do you want to protect your API from the latest trending attacks? Make sure you check back to the OWASP site periodically to see if an update has been posted.

3. Enable Encryption to Secure Your Traffic

What about preventing man-in-the-middle attacks? Be cryptic. Encrypt all API requests and responses. How? By using transport layer security (TLS), or what used to be known as the secure sockets layer (SSL). To work, this secure cryptographic protocol requires you to install an SSL/TLS certificate from a trusted certificate authority (CA) onto your web server. Once installed, this digital certificate will enable you to ensure that all communications running through your web-based HTTP API are encrypted (i.e., using HTTPS).

As a result, enabling encryption will:

  • Secure your API’s data transmissions to avoid unauthorized parties from intercepting and reading sensitive information like credentials,
  • Help you increase your customers’ trust by confirming to users that your API is legitimate and secure, and
  • Make your website automatically flagged as trusted by all major browsers.

insecure vs secure connection security indicators

The picture shows the difference between an insecure URL and a secure one.

Here is where it all begins with NIST’s secure software development framework. This is the first step that builds the foundation of your organization’s SSDLC. It’s where you ensure that all teams, processes, and technology are ready to include security in every step of your development process by:

4. Implement Strong Authentication Methods

How is your API going to verify the identity of whoever is using it? Don’t limit your authentication process to the usual user ID and password. Ensure that only authorized users can access your organization’s sensitive data and network by including one or more of the following methods.

HTTPS Based Authentication

A minute ago, we talked about how a web certificate will help you encrypt all your data transfers. Tap into its potential to prevent credentials decryption and interception. Make sure that your API login page uses the more secure HTTPS protocol and that the traffic goes through the standard port 443 instead of the insecure port 80.

For a secure authentication, the server will be configured to request a client certificate (i.e., PKI certificate or digital ID) to:

  • Verify the identity of the device through a digital certificate issued by a trusted certificate authority (CA),
  • Restrict access only to authenticated users, and
  • Establish an encrypted connection.

This is a popular method used by many organizations. For example, Microsoft’s API Management helps secure access to APIs and their back-end services, and Kubernetes is frequently used for many authentication-related operations.

example of apis encrypted authentcation

The graphic shows the most important steps in the HTTPS-based authentication process

API Key Authentication

This method of authentication uses API keys to verify that the app or system accessing it is legitimate. Is your API going to receive calls from servers only? Then this is one of the simplest and most efficient ways to secure your authentication process. Once implemented, a key pair, including a public and a secret key, will be added to each API request.

The secret key will then be used to create a unique, temporary token for each request. Why is it secure? The token can be used only once. Therefore, if an attacker manages to replay the same call, he’ll get an error message and won’t be able to access the API.

OAuth2 and OpenID Connect Authentication

Delegation is the keyword here. Both are based on the same concept of delegating authentication to third-party identity providers (IdP) and they will:

  • Allow users to use their login credentials from trusted organizations like Google, Apple, and Facebook.
  • Avoid users having to recall another password on top of all the others they already have to remember.
  • Enable you to transfer the security risk (and costs) to a bigger organization that’ll probably have more resources to dedicate to it.

Isn’t this a great opportunity for small/medium businesses and start-ups? So, how do OAuth2 and OpenID work together?

  • OAuth2 delegates the authorization to a third-party secure server that provides an access token to the user.
  • OpenID Connect adds another layer of security by adding an ID token (i.e., JSON web token) containing additional information about the user (e.g., ID, name, and login time).

The result of this collaboration? OpenID Connect: the API-friendly evolution of OpenID that has OAuth2 features already integrated within its protocol.

example of oauth2 and openid connect authentication

This is how OAuth2 and OpenID work together for secure authentication.

Do you want to know more about OAuth2 and OpenID? Check out Okta Developer’s entertaining illustrated guide explaining in detail how OAuth2 and OpenID connect work.

Tip: use an API gateway to easily control, further secure, and manage access to your back-end system and services.

5. Securely Manage and Store Your Keys

Do you remember what your mom said to you when she gave you a copy of your house key set for the first time? Probably something like, “Don’t lose them or you won’t be able to get in.” API keys give you access to the APIs’ functionalities and services. Lose them and, if you’re lucky, you’ll “just” lose access to your API. But if you aren’t so lucky, a hacker may find them and breach into your organization’s systems. Just like a thief would do to your house if they could get ahold of your keys.

To keep your API credentials safe, you can:

  • Use an API secret management service. This approach will enable you to securely store, manage and control your keys in the cloud. Do you work in a big team and are afraid that managing keys this way will be too daunting? No worries, secrets management tools (i.e., management services) are built to assist you in managing all your team’s keys in a breeze.
  • Generate new keys periodically. Keys can be compromised without you knowing it. For example, did you save the keys on the client side? A malicious actor could easily access them. Did you save your keys in your code? Never do that. What if you did and then forgot to remove them before publishing the project on GitHub? Congratulations! You’ve just given access to your credentials to everyone with an internet connection. Periodically regenerating keys and deactivating the older ones will help protect you from these risks.
  • Avoid storing your keys on the client side. Keys should be always stored in the most secure way possible. Some people choose to store them on the back end. How? All you have to do is to pass the fetched API results from the back end to the front end. This way, your credentials will be much more secure. Another option is to store them in a hardware security module (HSM), when applicable.
  • Restrict your API key usage. It’ll help you reduce the impact of a breach in case one or more keys are compromised. You can apply restrictions by IPs and referrer URLs to certain APIs or specific mobile apps.

6. Limit the Information You Share

People say that sharing is caring. That’s correct, but not when about it comes to the security of sensitive information. Have you ever seen some of the posters printed by the U.S. and UK governments during World War II to prevent information leaking? They’re all about keeping sensitive information away from the prying eyes and ears of the enemy.

With APIs and software development, you should take the same care. Because if you want to protect your data, it’s much better to share as little as possible. In other words: zip it! Here are a few helpful tips:

  • Limit the information displayed by error messages. Error messages should be as generic as possible to avoid revealing too many details that the attacker may be able to use against you. Rather than saying that the entered password is incorrect, you could say that they’ve entered an invalid username or password. This way, you’re not specifying which is incorrect
  • Use blacklists (blocklists) and whitelists (allowlists). This will help you limit access to resources. For example, you could use an API key whitelist to limit the access to your API. This will ensure that only the requests from IPs included on your whitelist can access your API’s endpoints.
  • Remove sensitive information before publishing your API. In August 2022, CloudSEK published a paper confirming that it discovered more than3,000 apps leaking Twitter API keys exposed thousands of accounts. How did it happen? The developers forgot to remove their authentication keys from Twitter API before releasing it. The report was all over the media. You may have dodged the bullet with your API this time, but you may not be so lucky in the future. Make sure you remove all sensitive information before making your API available to the public. No time to do it manually? Check the next point.
  • Use automated scanning tools. A scanning tool like GitGuardian or Secret Detection will help you automatically identify and remove API keys, passwords, certificates, and other sensitive information from your API before publication.

7. Validate All Inputs

People I know always say that I’m fussy and, sometimes, they’re right. However, being a perfectionist when building an API isn’t a negative thing. After all, your API is going to receive tons of requests every day. So, if you want to prevent attacks like code injection, XSS, and credential stuffing, be “fussy” and make sure your API checks every single request.

  • Use JSON or XML schema validation. Is your API using JSON or XML? Then make sure you use JSON schema or XML schema to ensure the payloads (i.e., the data included in the API requests) meet the schema’s criteria for validation. All unmatching payloads should be rejected. Think about a smartphone case manufacturing company. If the manufactured case (payload) doesn’t match the prototype (schema), it’s considered faulty and the case is rejected.
  • Test your API. Are you sure that all your input validation strategy has been implemented correctly? Test your API’s resistance level to invalid data types and formats to check it.

8. Implement Rate Limits Using Quotas or Throttling

Do you want to prevent DDoS and credential-stuffing attacks? Implement a rate limit to control the number of calls made to your API. It’ll also help you add stability to your app by controlling the amount of bandwidth available according to the capacity of your server. Because, sometimes, less is more.

Not sure how to implement this? Here are a couple ways:

Throttle API Requests

Throttling limits the number of requests your users can make against a specific endpoint (i.e., the point of entry where the call is received) for a set amount of time. As a result, this means a user can be temporarily disconnected or the response rate can be reduced.

Have you ever experienced a temporarily slower internet connection when surfing the net? If your internet provider temporarily reduced your bandwidth for one reason or another, that’s an example of throttling.

example of throttled requests

The graphic shows an example of throttling applied to an API endpoint.

Apply Quotas (Restrictions) to Prevent Overloads

Set a threshold to limit the number of calls a user can place in a specific time frame. You could set a quota of 8,000 calls per day. Once surpassed the quota, all requests will be rejected.

Tip: attackers may come from specific countries or use specific IPs. Why don’t you apply an even lower quota to those countries or IPs considered suspicious?

9. Use Firewalls to secure Your Network

Is your API behind a standard firewall? Good, but that isn’t enough. Manage your API traffic with the support of web application firewalls (WAF). To do so, you’ll have to configure your firewalls into two layers:

  • The demilitarized zone (DMZ) network layer. The DMZ network is the buffer area between two segregated networks delimited by two firewalls. This firewall will scan network traffic to detect threats, check for potential injection attacks, and perform other basic security activities.

demilitarized zone network layer

The graphic shows an example of a DMZ network layer.

  • The local area network (LAN) layer. This layer includes much stronger security mechanisms to check the content of the information going through the networks.

10. Log and Monitor Users Activities

Knowledge is power. Monitoring your API requests and responses will help you prevent breaches. There are many API monitoring tools available on the market. Among them, popular tools include:

  • Loggly. It features proactive alerting, customizable dashboards, anomaly detection, and reporting.
  • AlertSite. One of the most comprehensive REST API monitoring tools. It enables you to monitor the API layer and the user interface (UI).
But what do you do when the worst happens? How can you identify and close a breach before your CEO comes to your desk and politely invites you to pack up your things? Logs can save your bacon.

By logging all activities, you’ll be able to:

  • Trace back the root cause of the breach,
  • Fix the vulnerability, and
  • Amend your API to avoid similar attacks happening again in the future.

Your CEO will be happy and you’ll probably keep your job.

11. Embrace a Zero-Trust Model

In medieval times, kings were building walls around their castles to keep the bad guys away. Everyone living inside the castle walls was considered trustworthy. But how many times did attackers manage to climb the walls or enter the gate disguised as innocent travelers or peasants? The same was happening with APIs using a similar security strategy until the zero-trust model came to light.

With zero trust, no one (it doesn’t matter if it’s a piece of software or a person) inside or outside the perimeter is trusted until it/he has been

  • Authenticated,
  • Authorized, and
  • Constantly monitored.

It’s a bit like when you enter one of the government’s highly classified facilities (Area 51, anyone?): only a few thoroughly selected authenticated, authorized personnel can get in.

The zero-trust model is considered so valuable for security that has been recommended by the American National Security Agency (NSA) and included in the White House’s January 2022 national security memorandum. Its architecture has also been published by the National Institute of Standards and Technology (NIST).

Make sure you add it to your API security strategy because prevention is always better than cure.

We have now reached the end of our list. What do you think? Are these API security best practices worth a try? I’d give them a shot. Always remember that an API is a bit like the ATM machine; it’s an intermediary between you and your money in the bank that facilitates operations.

When you need to withdraw some cash you go to the ATM, type in your secret PIN number and, voila’, the machine gives you the requested funds. But just like ATMs can be hacked by malicious third parties to get access to your hard-earned dough, if not protected, APIs can be exploited to steal your precious sensitive data.

Final Thoughts on API Security Best Practices

DDoS attacks, code injection, stolen IDs, and passwords. Following the above-mentioned API security best practices will help you mitigate the risks of such attacks. OK, it won’t keep you 100% safe from hackers — in the digital world, nothing can — however, it’ll help you minimize the danger by mitigating some of the security risks.

Embed security into every step of the SDLC by using encryption and implementing strong security policies from the very beginning. A single API security vulnerability can have significant consequences. But with the right prevention tactics, tools, and forethought, you can address security threats before they arise. You know how to do it now — don’t wait until there’s a breach. Unleash the power of your APIs while keeping your organization and customers’ data secure.