Best practices for API gateway security

Written by:
Kuria Macharia

September 7, 2022

0 mins read

APIs are a critical component of today’s development landscape because of their importance in microservices. Since modern software is often composed of various microservices, certain functionalities may be beyond the scope of an individual API. With an API gateway, we can aggregate those services to behave as if they were a single API, and return complex responses from disparate microservices through a single call to an API gateway. For instance, with an API gateway and GraphQL, one can use a single defined schema to query unique data fields from different microservices and get a single unified response.

What is an API gateway?

An API gateway is an abstract layer that usually sits as the only public interface between microservices and consuming clients. It acts as a proxy for the back-end microservices, bridging the client-facing API endpoints, routing the client’s requests to the appropriate microservices, and aggregating the response data before sending it to the requesting client. It provides a consistent and coherent application program interface that simplifies the task for front-end developers. 

Other benefits that API gateways offer include:

Performing load balancing— We can configure an API gateway to provide load balancing support by distributing incoming client requests to the available service instances.

Eliminating round-trip requests— A gateway eliminates unnecessary client requests that can increase latency and result in poor performance. They can make a single request to the gateway, forward the requests to multiple services, and aggregate the responses.

Centralize usage monitoring and analytics— An API gateway allows us to integrate monitoring and analytics tools to collect and analyze valuable data related to user traffic, execution time, and errors. This information is essential when we’re making decisions about scaling and debugging an application.

API’s access to the backend services makes them an attractive point of attack for malicious hackers who want to access the backend services or intercept data in transit. An API gateway acts as a security barrier between the backend microservices endpoints and the client endpoints.

In this article, we’ll look at the security benefits offered by API gateways and explore the best practices to follow while taking extra steps to keep our API gateways secure.

How an API gateway increases security

Security is a crucial concern to companies that offer their services as an API. There are several ways in which an API gateway increases the security posture of systems utilizing public-facing API endpoints. These include:

Policy enforcement

Policies are rules that must be followed while accessing the underlying services and managing the API’s behavior. A policy contains two components — rule(s) to be checked and the resulting action. Enforcement of the policies is done inside the API gateway. We can customize them to fit the needs of different tasks such as authentication/authorization or traffic management. A good example of this is JSON marshaling and other forms of serialization of data, which we can standardize at a single point of entry.

Traffic overload protection

An API gateway can limit the number of times an API is called within a specified time. This ensures the backend request processing capacity isn’t exceeded. It protects the system from denial-cf-service (DoS) attacks, which involve flooding the backend microservices with traffic. It also protects the API from brute force attacks and trial and error attacks, where many requests with different credentials are submitted.

Circuit breakers

A circuit breaker adds to the security posture by ensuring that the connection to the backend services is secured. It works by stopping connections to the backend for a defined period of time if it detects a defined number of consecutive connection failures is reached. This prevents a backend from being overloaded with requests that are bound to fail. It is an automatic protection measure that prevents attackers from causing cascading API failures.

Decoupling of the backend services from the front-end applications

An API gateway enhances the security of sensitive backend services by eliminating any direct contact between them and the front-end applications. This also limits what the front-end can know about the microservices processing their requests. This protects the system from SQL injection attacks that involve directing malicious code to the back-end databases. Limiting what is known about the back end makes it harder for someone to initiate SQL injection attacks. That’s because they have no information regarding the database the information is coming from.

API gateway security best practices

An API gateway can mitigate the risk of injection attacks by implementing the basic input validation for all requests. This ensures that requests with suspicious entries are dropped before they get to the backend services.

While gateways offer excellent security capabilities — but we should also work proactively to keep our API endpoints and microservices secure. Let’s discuss some best practices to create a secure API gateway.

HTTPS and encryption of requests

To improve the security of an API gateway, we should first ensure its communication with clients is over HTTPS. HTTPS is a secure protocol that encrypts all data in transit, increasing its security. It is the current industry standard for public-facing websites.The TLS protocol is especially important when transmitting sensitive data by executions, such as logging into an email service, a bank account, or a company system remotely. It also helps us transfer the TLS management task from the client to the cloud service provider.

Implement API request validation

We should configure an API gateway to validate the API request received from the client before forwarding it to the backend microservices. For instance, we can configure a gateway to verify that a request parameter or header isn’t blank, or that the payload follows the allowed JSON schema.

If validation fails, the API gateway drops the request and returns an error response to the client. Doing this reduces the number of unnecessary requests forwarded to the server and mitigates the risk of injection attacks.

Set up logging

We should enable logging in an API gateway to help us solve client access and request execution issues. There are two types of logging that an API gateway performs: execution and access logging.

Execution logs contain details on each step followed by an API gateway in processing a request. The logged data includes execution traces, validation steps, and errors. Access logs contain the details of each entry into the API gateway. Each request creates an entry detailing who is accessing the API gateway and how they’re accessing it.

Implement rate-limiting

In an API gateway, we should implement rate-limiting to:

  • Prevent denial of service (DOS) attacks

  • Limit cascading failure impact

  • Limit resource usage.

Implementing rate limiting on the API gateway ensures that our microservices are safe from malicious traffic or genuine traffic overload that can cause a system failure. Throttling policy helps mitigate the downside of strict rate-limiting by queuing requests exceeding the limit for processing in the next quota. We can apply rate-limiting and throttling policies to a specified resource or all requests.

Enable web application firewall (WAF)

We can protect our API gateway using a web application firewall (WAF), which limits access to the API based on a set of defined conditions and rules. It helps secure the API gateway from common threats such as cross-site scripting and injection attacks.

For instance, we can use WAF to deny or allow access to requests from specified CIDR blocks, IP address ranges, or countries. It can also detect and drop requests containing malicious scripts or SQL codes. Implementing WAF allows us to move the security barrier closer to the client-side and free up the API gateway from unnecessary workloads.

WAF is an effective HTTP-level content filtering and it has even been recommended as one of the solutions to prevent attacks originating due to the Log4j vulnerability by US CISA. It’s also one of Snyk’s Log4Shell remediation best practices.

Designate API gateways

We should create separate API gateways based on their use cases to reduce the possible attack surface and ensure there’s no unnecessary exposure to API endpoints. Designating API gateways also helps minimize spreading in case of API gateway failure or throttling.

For instance, if there’s an attack on one gateway, it won’t take down all of the systems’ services. This makes debugging the system much easier because the attack surface is much smaller.

Getting the most out of your API gateway

The most significant step we can take to protect our API is introducing an API gateway.

It decouples the microservices architectures from the public-facing API and allows us to introduce different security barriers between them. These barriers — including rate limits, WAF, HTTPS, and request validation — mitigate the risk of common API attacks such as SQL injection, cross-site scripting, and denial of service attacks.

By adhering to the best practices such as HTTPs communication, request validation, logging, rate-limiting, WAF, and designated API gateways, we minimize the risk of successful attacks on endpoints and data in transit. Learn more about API security here.

Patch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo Segment

Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code. Supported by industry-leading application and security intelligence, Snyk puts security expertise in any developer’s toolkit.

Start freeBook a live demo