Securing Your APIs: Essential Strategies and Approaches

Matías Di Cola
Globant
Published in
7 min readJun 25, 2024
Photo by Bernd 📷 Dittrich on Unsplash

The Internet is a crowded city where millions of people, and even some machines, go about their daily lives. You’ve likely heard about the Application Programming Interface (API) on more than one time. If you’re here, it’s probably because you’ve heard mention of these APIs but still need to understand how they operate fully. This is understandable, as they’re not typically found on the surface of a website or application but rather constitute the internal workings that only developers can see and connect to make a tool function.

From a user’s perspective, the only thing perceivable about an API is the outcomes. For example, when you open a game on your mobile phone and can log into your favorite social network or when that app sends notifications to both your mobile device and computer. APIs are crucial because they make our online experiences more useful. Without them, plenty of connections would be much harder to create.

High level of how the APIs work. Source: k4sst.gitbook

An Application Programming Interface (API) is a mechanism that uses rules, protocols, and a set of definitions to work as the intermediary between two programs, allowing them to communicate. You can think of APIs like a restaurant, where the API acts like a waiter, taking a request from the client and fetching it to the kitchen. In essence, APIs are like friendly messengers who ensure that different parts of the internet and various digital systems can talk to each other and collaborate effectively.

Due to its inherent nature, APIs expose application logic and sensitive data, including Personally Identifiable Information (PII). Consequently, they have become an increasingly attractive target for malicious actors. With robust API security measures, the potential for rapid innovation would be greatly improved. The field of API Security is dedicated to developing strategies and implementing solutions aimed at comprehending and mitigating the distinct vulnerabilities and security risks associated with APIs.

This article will discuss the most important topics for protecting your APIs from vulnerabilities. We will cover critical subjects in API security, such as authentication, brute force attacks, encryption, auditing, and monitoring.

API Security vs. Traditional Security

Some key characteristics of API security vs. traditional security:

  • Traditional networks needed to protect only common ports like 80 (HTTP) and 443 (HTTPS). Nowadays, web applications have many API endpoints with different protocols, and each API can make security difficult.
  • When an API changes, traditional security tools need manual tuning and reconfiguring, which consumes resources and time. APIs evolve quickly in a DevOps environment.
  • Most APIs are accessed by mobile applications, services, or software components. Traditional security usually finds it difficult to exclude automated traffic from API endpoints.
Traditional Security vs. API Security. Source: Brightsec

Standard Web API Types

API security involves securing data transferred through APIs, normally between clients and servers. Some companies use APIs to transfer data and connect services. A compromised, exposed, or hacked API can lead to sensitive data leaks, such as personal data or financial information. Therefore, when APIs are designed and developed, security is a critical step to keep in mind and apply. Attackers could compromise all API data and functions if their provider was compromised before. Additionally, if the API isn’t properly coded and protected, it can be exploited across these weaknesses with malicious requests.

RESTful APIs

Representational State Transfer (REST) is a set of architectural constraints for applications that communicate using HTTP methods. APIs that use REST constraints are called RESTful (or just REST) APIs. The Anatomy of Web APIs REST was designed to improve upon many of the inefficiencies of other older APIs, such as Simple Object Access Protocol (SOAP). For example, it relies entirely on HTTP, making it much more approachable to end users. REST APIs primarily use the HTTP methods GET, POST, PUT, and DELETE to accomplish CRUD.

The RESTful design depends on six constraints: Uniform interface, Client/server, Stateless, Cacheable, Layered system, and Code on demand (optional).

GraphQL

Short for Graph Query Language, GraphQL is a specification for APIs that allows clients to define the structure of the data they want to request from the server. GraphQL is RESTful, as it follows the six constraints of REST APIs. However, GraphQL also takes the approach of being query-centric because it is structured to function similarly to a database query language

like Structured Query Language (SQL). GraphQL stores the resources in a graph data structure.

SOAP

Simple Object Access Protocol (SOAP) is a type of action-oriented API that relies on XML. SOAP is one of the older web APIs, originally released as XML-RPC back in the late 1990s.

Although SOAP works over HTTP, SMTP, TCP, and UDP, it was primarily designed for use over HTTP. When SOAP is used over HTTP, the requests are all made using HTTP POST.

SOAP API messages comprise four parts: the envelope, the header, the body, and the fault (optional).

Authentication and Authorization

Authentication and authorization methods are essential to protect the APIs in cloud environments. The authentication method validates the user’s profiles and the authorization method guarantees that users can only access resources that they are authorized to.

There are different mechanisms to perform “authorization” and “authentication” in cloud environments, such as those used by OpenID Connect, OAuth, and SAML. These mechanisms allow the integration of both processes (authentication and authorization) to ensure the security of API workflows.

Different levels of API stages and uses

In the next Python code for Authentication and Authorization in an API, we have a “How to” example to implement these processes in an API on a cloud environment using OAuth:

from flask import Flask
from flask_oauthlib.provider import OAuth2Provider
app = Flask(__name__)
oauth = OAuth2Provider(app)
@oauth.clientgetter
def get_client(client_id):
# Search client in OAuth database
client = OAuthClient.query.filter_by(client_id=client_id).first()
return client
@app.route('/api/resource')
@oauth.require_oauth('resource')
def resource():
# Access the protected resource
return 'Hello, World!'

Protection Against Brute Force and Code Injection Attacks

Cloud APIs tend to be vulnerable to brute force and code injection attacks. Attackers may attempt to either guess passwords with brute force or inject malicious code into the APIs to gain access to protected resources. Applying different security controls, such as brute force attack protections or data entry validation, can help prevent these issues or vulnerabilities. Automated security tools, like Web Application Firewalls (WAF), create an extra layer of protection against attacks.

Take a look at this Python code for data entry validation in an API example:

from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["100 per day", "10 per hour"]
)
@app.route('/api/login')
@limiter.limit("3 per minute")
def login():
# User authentication
return 'Hello, World!'

Data Encryption

Data encryption is an essential element of API security in cloud environments. It helps prevent the exposure of confidential data in transmission and storage processes. Security protocols in the transport layer, like HTTPS, provide a secure channel for data transmission. In addition, data encryption in REST mode, such as database encryption, provides an extra layer of protection.

This Python code example shows how to implement data encryption with HTTPS in a cloud API:

from flask import Flask
from flask_sslify import SSLify
app = Flask(__name__)
sslify = SSLify(app)
@app.route('/api/resource')
def resource():
# Access the protected resource
return 'Hello, World!'

Audit and Logging

Audit and logging processes are fundamental for keeping APIs secure on the cloud. The audit process allows continuous monitoring of API activities, and the logging process identifies suspicious or malicious events. API logging should include detailed activity information, such as the client’s IP address and type of request and response. All logs should be stored in a centralized and secure log management system.

This Python code example shows how to implement a logging audit process for a cloud API:

from flask import Flask, request
import logging
app = Flask(__name__)
logging.basicConfig(filename='api.log', level=logging.INFO)
@app.route('/api/resource')
def resource():
# Access the protected resource
logging.info('Acceso al recurso protegido de IP: %s', request.remote_addr)
return 'Hello, World!'

Conclusion

Ensuring the security of Application Programming Interfaces (APIs) within cloud-based environments represents the most important concern that warrants our unwavering attention. This requires a multifaceted approach for a range of security pillars, all collectively contributing to a robust and dependable API ecosystem.

API security in cloud environments is a critical issue to work on. Authorization and authentication, protection against brute force and code injection attacks, data encryption, and audit and logging are fundamental topics to obtain a high-security level to APIs. When implementing high-security processes and protection in your APIs, the integrity and confidentiality of data in the cloud are guaranteed.

In simple terms, when we focus on making our APIs secure, we’re making sure that the data stored in the cloud stays safe and private. It’s all about keeping data safe and making sure our systems work well.

References

  • HACKING APIS book — Corey J. Ball (ISBN-13: 978–1–7185–0244–4 (print), ISBN-13: 978–1–7185–0245–1 (ebook))
  • OWASP API Security Project

--

--