If you’ve ever geeked out and tried to find out how modern applications are developed, you have probably come across the term API. API (application programming interface) is a set of programming instructions that enables software components to communicate with each other. For example, your mobile application probably gets the latest weather data from the weather API hosted on the backend server used by your weather application.
APIs are an integral part of any tech organization. Companies spend about $590 billion a year integrating existing systems (a 2015 estimate), and various tech companies have offered over 24,000 APIs to date. Salesforce attributes more than 50% of its revenue to APIs; the same is 90% for Expedia.com. A massive chunk of a typical tech organization’s expense goes towards the research and development of APIs.
APIs handle sensitive and personally identifiable information daily, so they need protection.
Consider a financial institution’s web application that lets users check their account balance or transfer amounts.
After logging in, when you click on check balance, it contacts the following API:
https://vulnerbleBankingApp.com/checkMyBalance?id=123123123
Here, 123123123 is your account number. It then returns the account balance as the response.
The first attack avenue is that the API only takes the account number as a parameter. Even if you are logged in as user Alice, if you know the account number of Bob, you can provide the ID parameter with Bob’s account number to get his balance.
Similarly, if the API is insecure enough to use the same vulnerable format to transfer the amount, an attacker can use that to get free money!
Another vulnerable API:
https://vulnerbleBankingApp.com/transferAmount?to_id=123&from_id=456&amount=1
This is the API for when Alice (account number 456) is transferring $1 to Bob (account number 123).
But what if Alice is an attacker? Alice would replace the to_id with her own account number and from_id to Bob’s account number and exploit the vulnerable API logic to get the amount from Bob’s account.
Modern applications and APIs are not built this way, but API vulnerabilities still cause data breaches. A well-known example is the Facebook photo API exposure, which affected 6.8 million users. This post covers how to secure web APIs against these vulnerabilities.
Keep OWASP Top 10 API Vulnerabilities out
The Open Web Application Security Project (OWASP) is a nonprofit foundation that works to improve software security through community-led open source software projects. One of these projects is the OWASP Top 10 project, where they compile a list of the most common vulnerabilities in a domain.
When you test APIs for security bugs, check whether any of the OWASP Top 10 are present in your API. This step plugs the obvious vulnerabilities in your SaaS API architecture, especially for enterprise-level APIs.
Broken Object Level Authorization
In this vulnerability, an attacker obtains access to an object by breaching the security of other objects or data streams.
For example, an attacker can perform a GET request on accounts/id/financial_info on an API. Even if the attacker isn’t allowed to request a different id (id2), a breach is still possible. The attacker can successfully get the results for id2 by changing the value of id to id2 in the previous API call.
This can happen if the API backend is verifying the token but is not actively checking if the token is associated with the object that is being requested. A real-life example of broken object level authentication would be opening your neighbor’s door with your house key.
In most cases, the reason behind broken access control is improper permission assignments.
To prevent broken access control, perform authorization and verification checks and use the id assigned from the session instead of asking the user for an id.
Broken User Authentication
A weak way to prevent unauthorized access is to authenticate users with plain-text credentials taken from the API request. This enables an attacker to sniff credentials from the network and brute force credentials with API requests.
It is not uncommon for API developers to use default credentials on APIs to authenticate API users, which leads to broken authentications and security compromises.
One way to secure against broken authentications is to use random access tokens and short-lived tokens while rate-limiting API requests. The enterprise should use multi-factor authentication to protect accounts even when credentials have been compromised.
Excessive Data Exposure
Some APIs return more data than the application needs. One example would be a typical password reset functionality.
When a user requests a password reset for the user account “admin”, the client-side application requests the API for a one-time password. That OTP is sent to the account’s associated mobile number or email id. Additionally, the API also sends back the mobile number, and the client-side application will display a few digits to inform the client to which number the OTP has been sent.
Even if the client-side application filters the response, a motivated attacker can extract the complete mobile number/email address from the raw response. Error messages carry the same risk: an application bug can make the API return error messages that reveal information useful to attackers.
To prevent these bugs, never rely on client applications to filter data, and always confirm the use case before sending any personally identifiable information (PII) in a response.
Lack of Resources & Rate Limiting
Many APIs do not limit the requests a single user can make. In this vulnerability, attackers can send multiple requests until the backend is out of resources and cannot serve any other user. These attacks are more commonly called Distributed Denial-of-Service (DDoS) attacks.
These attacks try to overload a server and its surrounding infrastructure, which disrupts service for your consumers. Think of it like completely grid locking a lane of traffic on the highway so that no new cars can enter.
Developers should rate limit user requests and make sure they do not cause unnecessary processing.
Broken Function Level Authorization
In this vulnerability, a user can carry out tasks that are not permitted. Consider the following API call:
GET /useraction?deleteUser=all
Only the administrator should be able to delete users. But by discovering this endpoint, an attacker can send requests to delete all users without having the necessary permissions.
To prevent this vulnerability, the backend should check that the caller has proper authorization before performing any operation.
Mass Assignment
Some APIs that modify an object’s values process the input directly, without any checks. For example, the following call is made by a user to change the account name:
GET /changeAccountName?name=Bob
But malicious actors can specify additional parameters to compromise the integrity of the object. A malicious request would look like this:
Get /changeAccountName?name=Bob&AccountBalance=999999
To prevent this, developers should set read-only flags on properties that the input should not change. There should also be a proper rate limiter to eliminate the possibility of an attacker guessing parameters with brute force.
Security Misconfiguration
If applications you use in your backend are vulnerable and not kept up to date with security patches, attackers could exploit vulnerabilities present in the existing services to compromise the whole application.
To prevent this, keep all backend infrastructure and services used in the application up to date with all patches and run regular security audits.
Injections
Injection attacks are most common in web application breaches. According to the OWASP Top 10 project, injection attacks sit at the top as the most common vulnerability.
Injection attacks occur if the input from the user is wholly trusted and directly processed by the backend. They can result in several attacks such as SQL injection, XSS injection, XML injection, XPath injection, etc. They can also result in an attacker gaining remote command execution on your infrastructure.
The best way to prevent injection attacks is to sanitize input properly before passing it to the backend.
Improper Assets Management
An example of improper assets management is leaving legacy code on the application even if there’s no use for it. This oversight can result in a possible entry point for attackers if the legacy code is not maintained correctly. It can also compromise a newer, patched, and maintained application that uses the same infrastructure as the old one.
Run regular audits to keep track of your assets.
Insufficient Logging & Monitoring
Many large-scale deployments set up infrastructures for logging and monitoring to keep an eye on events related to the application. But because of poor design, logs are not properly monitored or integrated with security information and event management (SIEM) systems.
Securing Your API
With the OWASP Top 10 API Vulnerabilities covered, the next step in this checklist is how exactly you can stop attackers from exploiting these vulnerabilities in your API. Think of it like API governance: a set of standards and checks for your SaaS API management. The methods below protect your API from attackers and plug vulnerabilities that may have been created in the initial build phase.
Authentication
Use Json Web Tokens (JWT) or OAuth to authenticate your API.
Authentication through JWT relies on various details provided as a token with the API request.
A JWT contains a header, a payload and a signature, each Base64URL-encoded. The header and payload are JSON objects.
The JSON Web Token is provided with the request, so verification becomes easier. For verification, the server recomputes the signature over the header and payload with the shared secret key (HMAC), or checks it with the issuer’s public key (RSA or ECDSA), to ensure the signature is genuine. If it is genuine, it can be deduced that the data can be trusted. The authorization portion of the payload in JWT can be used to identify the user without checking every time.

OAuth allows websites and services to share assets among users. A typical example is a login page that offers the user more than one service to authenticate with. For example, the user chooses to authenticate with an email service website and is redirected to the login page of the email service.
After successful authentication on the website, the user is redirected back to your application but with an additional access token of the email service. That token can be used to verify user identity. OAuth can also be used to implement single sign-on (SSO), which improves the user experience.
Implementing JWT and OAuth
Because a JWT is only base 64 encoded, no sensitive data should be passed with JWT. The time to live—the expiration period for a token—should be as short as possible. Cryptographic algorithms should be hardcoded into the backend, providing no option for the client to change the algorithm. The JWT Secret should be random and complicated to make it infeasible for an attacker to brute force a secret key. If using OAuth, redirect-uri should be validated on the server side to make sure only whitelisted URLs are allowed. Also, while using OAuth, scope should be strictly defined and later verified for each request.
Access Validation
To prevent DDoS and brute force attacks on your API, implement a rate limiter so that only legitimate requests are served. A rate limiter caps the incoming requests to a web server. So, if an application is getting more requests than configured from an IP, the rate limiter will drop packets from that IP for a duration defined by timeout.
For example, in NodeJS, the Bottleneck package can be used to limit the number of concurrent connections as shown in the following code snippet:
const Bottleneck = require(“bottleneck”);
// Never more than 5 requests running at a time.
// Wait at least 1000ms between each request.
const limiter = new Bottleneck({
maxConcurrent: 5,
minTime: 1000
});
const fetchPokemon = id => {
return pokedex.getPokemon(id);
};
limiter.schedule(fetchPokemon, id).then(result => {
/* … */
})
In the same way, ratelimit can be used to implement throttling in Python-based APIs.
from ratelimit import limits
import requests
FIFTEEN_MINUTES = 900
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return response
Input Sanitization
Any application that accepts user input needs input sanitization. Even a single special character like an apostrophe (‘) can result in a security compromise.
Consider a login page that uses SQL database as its backend. The webpage first takes the input from the login page and transforms that input into an SQL query. For example, with username = bob and password = alice, the SQL would be generated as:
SELECT * FROM USERS WHERE user = 'bob' and password = 'alice'
However, as there is no input sanitization in place, attackers can log in to the website with any account without a valid password.
To perform the attack, they would pass bob’– as username instead of bob and any random string as password. So, the new SQL would be:
SELECT * FROM USERS WHERE user = 'bob''-- and password = 'hackallthethings'
As the ‘– in the username makes everything after the user field a comment, password checks become disabled, and the backend will allow the attacker to log in without a valid password.
NPM has a module, express-validator, that can sanitize form input before it is processed. The following example uses the express-validator library.
const { check, validationResult } = require('express-validator');
check('username', 'Username Must Be an Email Address').isEmail()
check('password').isLength({ min: 8 }).withMessage('Password Must Be at Least 8 Characters')
.matches('[0-9]').withMessage('Password Must Contain a Number')
.matches('[A-Z]').withMessage('Password Must Contain an Uppercase Letter')
With express-validator, you can use the isEmail() function to verify if the input is an email address or not.
Similarly, you can use check(‘value’).matches(‘regex’) to test if the input value matches the required input format specified by the regex.
from ratelimit import limits
import requests
FIFTEEN_MINUTES = 900
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200;
raise Exception('API response {}'.format(response.status_code))
return response
Conclusion
APIs are an attractive target for attackers and are predicted to become the top attack vector soon.
The only way to protect your API from attackers is to take proactive measures to secure your API design.
The best way to do this is to follow an API security checklist like the one in this article. Learn the current top vulnerabilities from OWASP or similar resources, then learn the methods that secure your API against common attacks and how to implement them. There’s a lot more to learn in API security, but this is a good starting point.
Put this into practice with Frontegg
Frontegg is customer identity and access management (CIAM) for B2B SaaS. It's free up to 7,500 monthly active users, including 5 SSO/SCIM connections.
Start for freeThe Complete Guide to SaaS Multi-Tenant Architecture
Read the guide




