5 API Gateway Best Practices

For a lot of organizations, APIs are almost like a digital baseball card collection. You keep adding to it, and some of them can be monetized. Just as you need to organize and protect your most valuable cards, you need to implement the appropriate security measures around your APIs. Your API gateway is like having a dedicated binder or box just so you can access your cards and share them without exposing them to people’s hands in a way that can devalue them.

 

API gateways are one critical component of securing your connected environment. By understanding API gateway best practices, you can incorporate them into your overarching API security program.

What is an API gateway?

An API gateway acts as a single entry point for all incoming API requests. It separates clients and their backend services by ensuring that the right requests reach the right services so that responses are returned as quickly as possible. Implementing an API gateway enables organizations to:

  • Provide front-end developers with an easy-to-use interface
  • Improve system efficiency with built-in load-balancing features
  • Optimize server resource utilization
  • Reduce the attack surface by limiting direct internet access to backend services
  • Intercept and filter out malicious traffic

 

What are the security benefits of an API gateway?

API gateways are one part of a larger API security program. By sitting between clients and their backend microservice endpoints, the API gateway can act as a barrier that limits exposure to the public internet.

 

Some benefits that API gateways provide include:

  • Authentication: Using token-based protocols like OAuth 2.0 and JSON Web Tokens (JWT) enable organizations to apply the principle of least privilege to APIs.
  • Policy enforcement: Policies define API’s rules and resulting activities, like authentication, authorization, and traffic management.
  • Traffic management: Limiting the number of times a service can call an API within a defined timeframe mitigates risks, like those arising from Denial of Service (DoS) and brute force attacks.
  • Circuit breaker patterns: These mechanisms detect connection failures and stop backend connections to mitigate the services from being overloaded.
  • Limit sensitive data access: Separating the backend services that contain sensitive data from the front-end applications limits the data shared between them, mitigating security risks like SQL injection attacks.
  • Data encryption: Encrypting data at rest and in transit mitigates interception and tampering risks.
  • Request validation: Specifying the backend service and what the response contains limits the information returned to the front-end application.
  • Monitoring and logging: Capturing and monitoring data about incoming requests and outgoing responses helps detect suspicious activity that can indicate a potential security incident.

 

How API gateways operate

An API gateway sits between the public internet and your APIs, directing requests to the right backend service. While they protect the APIs from the public internet, their capabilities are limited to screening incoming traffic and requests.

 

Deployment

Depending on your company’s unique requirements, you can deploy the API gateway:

  • On-premises: housed within your data center, enabling more control but also increasing costs
  • Cloud: managed by a cloud service provider, reducing costs and accelerating deployment
  • Hybrid: user interfaces, developer portal, and analytics accessible in the cloud, but vendor manages availability, uptime, and maintenance

 

How it works

APIs enable applications to share data. For example, your customer relationship management (CRM) tool may connect to your accounts billable tool, connecting customers with invoices and payment processing. When a user takes an action in one application that relies on information from the second application, the API gateway steps in to help them communicate by:

  • Authorizing and validating the request made in the first application
  • Transforming the request for the backend endpoint, like applying the appropriate HTTP headers, query strings, or API keys
  • Routing the request to the relevant service, like a database or other application
  • Transforming the response in a way that makes sense to the initial requesting technology

 

In more complex situations, the API gateway routes a request to multiple services then combines all the results into a single response.

 

5 API Gateway Best Practices

Your API gateway enables you to put public-internet-facing controls and guardrails around your APIs. While this outside-in approach only solves half your problems, it remains a fundamental technology for mitigating data breaches and privacy risks.

Identify All APIs

All APIs should be behind the API gateway to reduce the attack surface. While the API gateway may not be able to identify them for you, you should implement a continuous API discovery solution that can:

  • Scan all API traffic at runtime
  • Categorize API calls
  • Sort incoming traffic into domain buckets based on your top-level domain
  • Provide automated risk assessment scoring

Implement Authentication and Authorization

When you implement authentication and authorization, you restrict how the application interacts with the backend resources. You should consider the two main use cases:

  • Between services: Since services have no human interaction, you should create a service account and key that the calling services uses, then a JWT with this private key can send the signed token in the API request.
  • Users: Using OAuth 2.0, the application authenticates the user through the organization’s identity provider with a JWT token so that the resource server can validate this through an Authorization header.

 

Use Request Validation

Validating the inputs mitigates injection attack risks by ensuring that all incoming requests follow specific JavaScript Object Notation (JSON) schema and formatting rules. A simple example for defining the schema might look like this:

 

schema = {
'type': 'object',
'properties': {
'username': {'type': 'string', 'minLength': 3, 'maxLength': 20},
'email': {'type': 'string', 'format': 'email'}
},
'required': ['username', 'email']

 

The validation of username and email field might look like this:

username = data['username']
if not isinstance(username, str) or len(username) < 3 or len(username) > 20:
return jsonify({'error': 'Invalid username format'}), 400
email = data['email']
if not isinstance(email, str) or '@' not in email or '.' not in email:
return jsonify({'error': 'Invalid email format'}), 400

In this case, the API won’t validate the request and allow it to reach the backend service if the email address does not include an “@” sign, meaning attackers need to include this character.

 

Use HTTPS Communication

HTTPS encrypts the data traveling through the API and gateway. When implementing this security control, you should:

  • Configure the API gateway to generate client certificates
  • Configure the API to use Secure Sockets Layer (SSL) certificates
  • Test to ensure that the client certificate works as intended
  • Configure the backend service so that it verifies the API gateway’s client SSL certificate

 

A simplified example of what this backend service verification might look like would be:

def secure_endpoint():
if request.environ.get('SSL_CLIENT_VERIFY') != 'SUCCESS':
return jsonify({'error': 'Client certificate verification failed'}), 403
client_cert = request.environ.get('SSL_CLIENT_CERT')
return jsonify({'message': 'Client certificate verified successfully'}), 200
if __name__ == '__main__':
ca_file = 'path/to/ca_file.pem'
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_verify_locations(cafile=ca_file)
ssl_context.verify_mode = ssl.CERT_REQUIRED

In this example, where “ca_file” is the certification authority file, the route function will check to verify the certificate. If that verification fails, then the backend service returns a 403 error.

 

Limit Requests

Setting thresholds for API requests enables you to mitigate risks arising from DoS attacks and other activity that overwhelms system resources. You should consider the following throttling limits:

  • Burst: the number of concurrent requests that your API can handle
  • Rate: the number of allowed requests per second

Implement Monitoring and Analytics

Your API gateway can capture data and provide analytics that enable you to understand patterns and traffic anomalies indicating a potential attack. Some key data that you want to collect include metrics for a defined time period around:

  • API Calls
  • Cache hit
  • Cache miss
  • Latency
  • Integration latency
  • 4XX errors
  • 5XX errors

 

Further, you should integrate this logging and monitoring into your overarching security monitoring strategy for holistic visibility into your controls’ effectiveness.

 

Graylog API Security: Augmenting Your API Gateway

Graylog API Security is continuous API security, scanning all API traffic at runtime for active

attacks and threats. Mapped to security and quality rules, Graylog API Security captures

complete request and response detail, creating a readily accessible datastore for attack

detection, fast triage, and threat intelligence. With visibility inside the perimeter,

organizations can detect attack traffic from valid users before it reaches their applications.

 

Graylog API Security captures details to immediately identify valid traffic from malicious

actions, adding active API intelligence to your security stack. Think of it as a “security

analyst in-a-box,” automating API security by detecting and alerting on zero-day attacks

and threats. Our pre-configured signatures identify common threats and API failures and

integrate with communication tools like Slack, Teams, Gchat, JIRA or via webhooks.

 

Get the Monthly Tech Blog Roundup

Subscribe to the latest in log management, security, and all things Graylog blog delivered to your inbox once a month.