API Security Best Practices to Protect your Business

This comprehensive guide discusses API security best practices to protect your applications against API security attacks and safeguard data.

December 10, 2020
11 mins read
Last Updated November 22, 2022
API Security Best Practices

API Security Best Practices to Protect your Business

API brings many benefits to the table along with playing a major role in software and application developments. According to Gartner, by 2022, API attacks will rise considerably for enterprise application data breaches each year. So no wonder several IT decision-makers today are scratching their heads about API security. This year, attackers have doubled their activities during the Covid-19 pandemic and managed to exploit every possible avenue to spike API attacks claiming victory over vulnerable data across the globe. In April alone, this survey found a 667% increase in malicious phishing emails sent by hackers impersonating the UK authority, CDC, and WHO during the pandemic. 

The security enigma around APIs is why most experts recommend following industry best practices. APIs have become imperative for enterprises. However, the financial incentive and agility of APIs become worrisome with unnecessary exposure to precious information. 

According to Erez Yalon, Director of Security at Checkmarx and project lead at the OWASP API Security Top 10, told The Daily Swig that authorization and improper asset management are two key areas of particular concern while dealing with API security:

“Authorization tools are complex because the implementation does not take place in one location, but in many diverse components like configuration files, on-premises software and app codes, cloud, hybrid deployments, and API gateways.” 

It might look like simple maintenance with a basic understanding of the APIs, a well-organized inventory, and documentation, but API security is more complex. For starters, OpenAPI Specification is highly recommended. It’s critical in the world of APIs, and it helps developers block shadow APIs and extreme data exposure.

Yalon further added that modern web and mobile apps have many roles and users. This makes it challenging to execute safe object-level and function-level authorization mechanisms. In the matter of asset management, he observes that even a lack of proper documentation for APIs can create chaos in favor of the rise in security vulnerabilities.

This article helps you understand the top 10 API security best practices to know how you can safeguard yourself effectively:

Simform provides excellent API integration services with security and efficiency to make sure your systems are secure and work together seamlessly. To avail our expertise in a large variety of APIs, contact us today!

What is API Security? Why is API Security Important?

Whether you have a web or mobile app connecting you to your company, customers, stakeholders, partners, or investors, your client-side of the app interacts with the server-side via the Application Programming Interface, popularly known as API. 

This means API security must be airtight and robust in design, architecture, process. After all, it’s the security ecosystem that’d safeguard the data of your organization and your customer and be future-ready.

By using APIs, companies may inadvertently open up the door to all of their corporate data,” -Chris Haddad, chief architect at Karux LLC. 

As discussed, APIs’ goal is to connect and let the client-side interact with the server-side to transfer data safely. However, APIs can be misused during these data exchanges, – here’s where data-breach attacks and hacks happen. It exposes your personal, professional, financial, medical, and private data leading to a dramatic loss of credibility and breach of trust with your customers.

API Security Best Practices

In today’s era, cybersecurity and data breach due to API is taken very seriously. The damages to an individual, organization, industry, or the economy of whole countries can be devastating and plenty. Not a day goes by where we don’t use apps and APIs for emails, shopping, banking transactions, or digital wallets to pay for our products or services. All this brings us to the elephant in the room. Is your API safe enough? or are you protected from API security attacks?

An eye-opening data breach incident was reported in 2018 with web API for USPS corporate database in which over 60 million corporate users’ account numbers, email addresses, residential addresses, and phone numbers were leaked, but the matter went unaddressed for a long time.

Imagine the chaos this can create with mere two apps interacting or integrating to fulfill customer-service requirements. Bam! You’ve fallen into that trap.

API metadata provides the entire attack surface for an API, making it easier for hackers to know or find possible vulnerabilities -Ole Lensmar, chief technology officer at SmartBear Software.

API Security Best Practices

The implications of API security risks can be huge, including the infamous Cambridge Analytica breach, where a Facebook API loophole exposed the personal information of 50 million users. The most severe API security risks include user-and function-level authorization, broken object level, absence of right resources, excessive data exposure, security misconfiguration, and inadequate logging and monitoring. Let’s dive in and understand the API security best practices of the industry:

1. Inappropriate Assets Management

API Security Best PracticesCreating proper and updated documentation is essential for APIs as they can expose more endpoints than conventional web apps. A record of deployed API versions and fitting hosts can help mitigate general IT security threats such as deprecated API versions and risky debug endpoints. 

Compared to UI-based web applications, a web API usually exposes added endpoints that are less at risk, particularly for decentralized deployments spread across various services or microservices. Unfinished or outdated asset inventories and documentation can lead to skipped endpoints. This way, you might be increasing the chances of attacks on your assets. Inappropriate control of versioning and deployment also leaves retired API versions running beside current versions. Unpatched older versions make for an easy target and often end up providing access to data.

This best practice is recommended also to create an inventory and document all API hosts and APIs. Secure a clear division between the production environment and others. Make documentation a priority in the daily process to ensure it’s always updated. Also, avoid obtaining production-data sources of non-production environments.

2. Defective User Authentication

API Security Best PracticesAuthentication mechanisms are often executed incorrectly, enabling attackers to compromise authentication tokens or worse – exploit implementation flaws to temporarily or permanently assume the identities of other users. Simply put, compromising a system’s ability to identify the user compromises the overall API security.

Attackers can easily access user accounts to extort sensitive data, mimic users, steal money, or overtake the user account. In Fintech apps (banking or digital wallets), authentications play an influential role while carrying out transactions. This can expose your financial and credential info leaving you vulnerable to a crippling loss.

All authentication mechanisms must execute sufficient protection, including robust credential encryption, login-trial limiting, and appropriate authentication-token validation. In this scenario, the best practice is using encrypted JWT tokens. 

Any online service or mobile app where you put in your credit card number can be affected by API abuse. The most common things such as credential stuffing and abuse of the business logic, like verifying email addresses, credit card numbers,” said Zane Lackey, co-founder, and CSO of the cybersecurity company Signal Sciences. 

The authorization and authentication are a complex and challenging mechanism for APIs. Because authentication endpoints reveal to anyone by design, endpoints for user authentication should be administered uniquely from standard API endpoints. Implementing some extra layers of protection is a smart call for credential-stuffing attempts along with token-guessing attacks and brute-force passwords.

3. Broken Object Level Authorization

API Security Best Practices

The challenge is a constant hanging sword of an inadequate authentication or poorly applied process. Improper authorization of API leads to exposed and vulnerable assets accessible from the web. That means appropriate authorization protocol and best practices were not followed. 

Attackers can misuse API endpoints of broken object-level authorization by planning the ID of an object transferred within the client request. This means the client can request information from an API endpoint that they’re not supposed to access. This attack typically leads to unauthorized information disclosure, modification, or destruction of data. APIs have a tendency to vulnerability due to endpoints and controlled object identifiers. This is where it creates an exposure on the surface Level Access Control issue.

Ben Waugh, the chief security officer at the healthcare data integration company Redox, says, “What I see more and more of, SIM swapping, SMS-based multifactor authentication is not enough and not effective anymore.”

Inspections for object-level authorization should be mandatory in each function that accesses a data source utilizing every input from the specific user. Choosing the authentication model that best suits your API demands, adding an extra layer of authentication methods, and encryption for your base authentication design should be the ultimate goal.

All code that accesses objects via an API should include authorization checks. Failure to do so typically leads to an unauthorized data leak, unofficial modifications, and deletion of entire data or a user. Conversely, to place assets in API-accessible cloud storage, you need to ensure that all access attempts require appropriate authorization.

4. Unreasonable Data Exposure

API Security Best Practices

Developers may unintentionally expose all object properties without noticing the sensitivity of these properties. Sometimes, instead of relying on the clients for data filtering before displaying it to the user, they fall into this trap. The accidental exposure of data from the API could adversely affect in many ways— leaking of sensitive data such as gender, location, financials, medical history, etc.

Another case in point: In 2018, FIESP- Brazil’s largest professional industrial enterprise, cited exposure of data for over 130,000 companies containing 34.8 million entries. The data hack included names, social security numbers, identification, home addresses, emails among others.

Any APIs implemented before a precise specification is dangerous. The generic implementations of API exposing all object properties make sensitive data vulnerable to personally identifiable information (PII). Such as API endpoint, which always returns to finish a JSON user object even if the client’s app only requires a few attributes.

Carefully audit all data responses to ensure that only the relevant data fields are exposed. Overall, the general word of caution is to avoid coding defaults that publish an object’s data-fields by default. Deliberately choose the areas that display in all cases. API endpoints should perform data filtering to restore only those properties required as per a specific use case. Testing should not miss out on validating all API replies to limit unnecessary exposure.

5. Security Misconfiguration

API Security Best Practices

Today’s systems are tricky enough to understand how to authorize the roles or groups and allow which user hierarchy to give access privileges. A typical example is one of the APIs using Amazon Web Services. AWS system releases data processing jobs to S3, but the S3 bucket might be given insufficient permissions. Say, API is secure, but the data output is written to S3, because of misconfiguration. The data is in danger, so even the API is not secure.

Security misconfiguration is usually the result of weak default configurations, misconfigured HTTP headers, needless HTTP methods, and tedious error messages carrying sensitive information. Misconfiguration can also result from other common concerns like permitting Cross-Origin resource sharing, half-done configurations, and sometimes even open-cloud storage.

The best practice here would be to test and document external and internal systems for any misconfigurations. This should be a common practice for all categories, all varieties of issues over the entire technology stack which can disclose sensitive information or become a bottleneck for extra attacks. Additionally, the default configurations with none or insufficient authentication fail to reinforce HTTPS, omit useless HTTP methods in place, withhold vital HTTP security headers, and more.

Define and use a repeatable method to deploy accurately challenging environments. Avoid overly authorizing, cross-origin resource sharing (CORS). Reinforce and test security across the whole API stack, especially to cloud-storage permissions.

6. Broken Function Level Authorization

API Security Best Practices

Defects in functional level authorization can occur from complicated access-control policies, various hierarchies/roles/groups, and a difference between regular and official functions. These problems allow intruders to gain access to users’ resources and administrative tasks. A good example is the world-famous Facebook notorious breach due to a functional photo API exposure, which was left unattended for more than a year exposing 6.8million users and 1500 apps in the process.

Every call for API function should need the authorization to make sure that the current user is authorized to execute a specific object’s specific function. If implemented inaccurately, users may call functions that are not required or relevant. Try to manually change function names in URLs or HTTP methods, which is not needed. These defects will expose unnecessary functionality to cyber-attackers often targeting administrative functions. Another best practice is to utilize a consistent and uncomplicated authorization mechanism.  Ensure that you deny all access by default and assign required explicit grants according to the roles and functions.

7. Mass Assignment

API Security Best Practices

JSON is bound to encounter data flaws without using proper filtering properties. Intruders can modify object properties that they’re not supposed to by merely exploring API endpoints, presuming object properties, studying documentation, or using call payloads for additional object properties.

Restricting or limiting without a proper filter mechanism or whitelist process can confuse data models leading to a mass assignment. These hacks can easily occur via penetrating and changing properties for all objects, endpoints, or even object-properties. 

For example, Venmo had a data breach and made a blunder in API security; Venmo is “social” by design. The payment platform shares all transaction descriptions by default and asks users to opt-in to keep their data private. Many of the explanations of Venmo transactions were transparently explaining personal activities, but many users were not even aware of Venmo’s public policy. At the same time, Venmo responded that their API function was intended in that fashion to keep it public. Well, it was a classic example of poor security by design and, unfortunately, still is. In this case, the ‘breach’ came from the fact that the API  was unsecured, allowing for the mass scraping of 200 million transactions. This breach included data such as the full names of users/senders, the memos of all trades, the transaction’s value, and more.

Some API calls request or modify property probably more than just once, and sometimes all request parameters are very rare in this scenario, but if this is automated, it can create a massive disaster in seconds. If not properly regulated, API endpoints can end up granting access to properties that may be beyond the authorized scope, enabling attackers to get a foot in the door of your database. Avoid directly mapping client data to internal variables as an API security best practice.

8. Code Injection

API Security Best Practices

It’s an attack of any kind where core code is injected to extort data, spread malware, and interrupt your API’s healthy functioning. Violators attempt to supply malicious data to the API endpoint, expecting that data will be sent directly to them by the executed code. Without proper validation, API input might provide whatever the intruder was looking for. All the standard-injection attacks apply to OS command injection, NoSQL, SQL, and LDAP injection. 

Harmful outcomes range from information exposure to DOS and remote code execution as well. Injection errors occur when a query or command creates untrusted data and sends it to an interpreter. Malicious data from an aggressor can trick an interpreter in this scenario into accessing data without explicit authorization or even performing unintended commands. In 2019, disasters from many ecommerce platforms reported a 70% increase in DDoS cyberattacks on Black Friday and 109% on Cyber Monday, making holidays an easy target exposed and vulnerable against an influx of malicious code injection. 

The best practice for this is to filter all inbound inputs. Limit the number of customizability and eliminate free-form entry of structured data storage. Filter by using a whitelist, verify, validate, and encode all inputs from API requests. This includes both client-side and incoming from external systems. Also, utilize parameters for APIs to restrict inputs. Avoid directly applying external inputs in queries, object-relational mappings, XML documents, or OS commands.

9. Insufficient Logging and Monitoring

API Security Best Practices

Most security breaches are only discovered days or even weeks after they’ve occurred. Determining what data was affected, what systems were compromised, and what steps need to be taken to remediate the situation depends on having useful logs of access, security alerts, and user activity. The most abused security vulnerability these cruel hackers rely upon is an insufficiency of logging and monitoring to jeopardize data without raising an alarm. By the time these breaches are detected, it’s too late. In that case, attackers will most likely cover their actions to execute multi-stage attacks.

If logging and monitoring are performed with missing or useless integration with incident response, it lets intruders attack systems. It gives them enough legroom to impersonate users, tamper with more systems, and even obtain or destroy user data. Anand Prakash reported a similar incident about Uber in the same context wherein millions of user accounts were vulnerable and lacked appropriate monitoring. It can certainly be a daunting task to keep track of all access to API endpoints across thousands of assets if the access to APIs and their infrastructure is not monitored and logged correctly. 

The best practice recommended by experts here is to establish a data retention policy, including how far you’d prefer to store the backlogs. Enable your API access actions to register and record crucial metrics and events. Make sure to save logs in searchable and easily indexable formats.

It is best to keep detailed and protected logs of all access trials. Experts also urge you to adopt a system to monitor logs, including the whole API stack constantly. It is also wise to configure alerts beforehand to secure a timely incident acknowledgment for any questionable activity.

10. Lack of Resources and Limited Rate

API Security Best Practices

APIs often don’t impose any limitations on the number of resources or size requested by the user. Unfortunately, this impacts the API server performance, turning to Denial of Service and leaves ajar the door of opportunity to open authentication flaws like brute force attack.

When you don’t have a skilled resource to monitor regular checks and limit the API-data sharing or even safeguard authentication tokens, you will likely be doomed by assumed-user identity who might exploit these flaws. This will compromise the security of that user, along with many users, and the overall API security.

Default configurations for many public APIs don’t restrict API clients from accessing rates-requested resources. One reason is the practical limitations that might not be included during the design phase. Exploitation could eventually lead to resource exhaustion and, ultimately, a denial of service. Similar behavior for brute force attacks and credential stuffing is used to trigger excess errors. Include rate limits and size in API specs and implementations. Additionally, set resource caps for runtime environments and continuously verify queries and call parameters.

Venmo isn’t alone. APIs are a significant security mess for several companies. According to a survey released last year, 60% of companies have 400 APIs or more than 46%. 51% of companies aren’t sure their security teams are aware of APIs, and 45% aren’t sure if a malicious entity is accessing their APIs. “Security leads need to get involved with the API development,” says Humberto Gauna, a BTB Security consultant.

Security Best Practices for Web APIs

Web APIs give interfaces between web servers and web browsers and are among the most popularly-used API types. 

The OAuth 2 protocol comes in handy when you need to restrict access to API endpoints. Clients must primarily log in to a particular open endpoint and give their API credentials. The server authenticates the clients and grants them a token to access restricted endpoints.

You can apply cryptography to control access to the signatures of hash message authentication code (HMAC). Classified cryptographic keys inside the signature verify data authenticity of messages. When a client device attempts to call the API, this hashed message creates a signature. The server hosting the API call then recovers a signature from this secret key saved on the server. If both signatures match, only then the request is authorized.

Digital-signature exchanges help you protect secret keys utilized by clients and API servers. Additionally, they make it feasible to authenticate API calls. When a client initially calls the API server, the signature’s public key gets validated against the similar private key on the API server to confirm the call’s authenticity. 

Another original attribute that assists you in securing your Web APIs is statelessness. It compels the clients to pass the message context to the API server of a service provider and give credentials that the server can confirm before processing.

Security Best Practices for REST APIs

Another classic Stateless API, just like Web APIs, is the Representational State Transfer (REST) API. It gives interoperability within online computer systems. There are various ways to guard REST APIs. Be cautious – avoid applying passwords, session tokens, usernames, and API keys in URLs where web-server logs can store them and provide cybercriminals opportunities. You’d want to use a hashing algorithm to create password hashes that convert passwords into unreadable characters. 

Program your API servers to match the current time. This means documenting the request timeframes of API requests and accepting requests only if they occur within a reasonable timeframe. This restricts brute force strikes on your API server.

The SSL and TLS  cryptographic protocols simplify authentication credentials to create random access tokens for the username fields of HTTP basic authentication during API requests. If you practice HTTP 2, your API servers can bypass handshakes on the following requests.

By limiting the access to HTTP services, OAuth 2 assists with Web APIs to shield REST APIs. The protocol specifies any sort of third-party access by harmonizing approvals between HTTP services and resource owners. Validate request parameters before requests contact your app’s logic. Don’t forget to add necessary validation tests and reject requests promptly if validation misses.

Extra Layer of Security to API Gateways

The API gateways can give a layer of protection for your APIs. While you develop security policies, there are a few imperative fundamental guidelines to consider such as identity access management (IAM) to perform least-privilege-access building, rendering, updating, and erasing APIs. This applies to scenarios in which we access payment gateways on various platforms to complete financial transactions. It is particularly crucial to add that extra layer of security to safeguard your company’s compliance and user’s sensitive data. 

Another crucial security aspect is to evaluate if the configurations comply with your internal-governance policies. Also important is how the resource configurations and connections of your API gateway compute support transformation over time. Set up alerts to be notified if a resource breaks a compliance rule. Ensure you monitor API security by setting alarms to follow each API gateway’s metrics over a particular period. 

In case the metric surpasses a given origin, configure the system to transmit notifications to the security or compliance policy. It can automatically request the required security action. Be sure always to log all requests for your APIs to monitor user activities as part of your exercise by role and service. By tracing the records, you will identify requests to the API gateway, the IP address that made requests, and each request with time/date.

Closing Thoughts:

In the post-covid-19 scenario, many enterprises have opted for the ‘Zero Trust‘. This is just the start – the list of cybersecurity compliance is a long, overwhelming one including GDPR, HIPAA, FISMA, CSF, PCI DSS, and NIST. So now, each security professional must bring on their A-game to safeguard their organization’s data. Please don’t hold back until it’s too late. Speak to an expert and put your mind at ease.

At Simform, we work hand-in-hand with you to develop and integrate various custom APIs and 3rd party APIs for custom software, web apps, and mobile applications. Our API integration projects aim to save you a ton of money by reducing development time and cutting costs.

Have more questions? Get in touch with our experts


Comprehensive guide to simplify cloud migration

Working from last 10+ years into consumer and enterprise mobility, Hardik leads large scale mobility programs covering platforms, solutions, governance, standardization and best practices.

Your email address will not be published.