Application programming interfaces (APIs) are a strategic necessity to give your business the agility, innovation, and speed needed to succeed in today’s business environment. However, the financial incentive associated with this agility is often tempered with the fear of undue exposure of the valuable information that the APIs expose.

With the rise of APIs also comes the potential for more security holes, meaning coders need to understand the risk to keep corporate and customer data safe. According to Gartner, by 2022, API abuses will be the most frequent attack vector for enterprise web applications data breaches. It is no wonder that many IT decision-makers today are concerned about API security.

In 2018 itself, there have been more than half a dozen headlines of data breaches where APIs were listed as the exploited mechanism to extract data illegally. Hackers are sophisticated and are constantly looking into new ways to break down defences and access valuable data. Taking the appropriate security measures throughout the design process can ensure that your API is used properly by those you allow to interact with your application.

In this article, we’ll take a look at API security best practices, and discuss strategies for securing APIs.

API Security Best Practices
If you are building an API for public use or even only for your internal services, the following needs to be considered before augmenting any additional security layer or technology.

Authentication: API authentication means determining that the client application has an identity that is allowed to use the API. The API must be able to authenticate itself to the apps which consume it. Likewise, when your API interacts with servers, they must authenticate themselves to the API. Tokens should expire regularly to protect against replay attacks. Most enterprises will use an internal database or Lightweight Directory Access Protocol (LDAP) authentication store, though OAuth may be a better option for highly public APIs.

Multi–factor Authentication (MFA): An MFA requires a user to use a one–time usage token they receive after authenticating with their credentials. The user may also have a digital key which is a token that the app can validate. When the app receives the token which it validates with the MFA provider, it proceeds to consume your API. Tokens are usually issued with an expiration period and can be revoked.

Authorization: Authorization is determining the scope of interaction allowed — that is, what actions and data the authenticated application has access to when using the API. This is typically best handled by application logic, for example, using an access control framework, such as Open Authorization (OAuth). However, it is best to augment this functionality using an API gateway. The following two ways are also used for defining the level of authorization required by the user:

  • Role–based Access Control (RBAC): Static assignment of roles to users based on the organizational groups to which they belong. Groups are role and app agnostic; they are purely business–level decisions. In RBAC, an app uses roles to assign degrees of access to groups of users which the role represents.
  • Attribute–based Access Control (ABAC): ABAC aims to facilitate the dynamic determination of access control based on circumstantial information available at the time of the API call.

Make security the number one priority: Developers often have a feature–driven mindset, where functionality takes precedence over security. Unfortunately, in today’s security landscape, vulnerabilities and threats lurk at every corner and have ever–growing consequences, so we have to turn this on its head.

Encryption: Secure Sockets Layer and Transport Layer Security (typically referred to as SSL/TLS) encryption is mainstream and should be used for both public and internal APIs to protect against man-in-the-middle attacks, replay attacks, and snooping. For external APIs, the web server can handle this directly or a reverse proxy can be employed. A service mesh can be used for internal APIs to add automatic encryption on top of service discovery and routing.

Protecting your API: Developers must ensure that the API properly validates all input from the user to prevent Cross-site Scripting (XSS) and Structured Query Language (SQL) Injection. There are many ways to protect against these types of vulnerabilities including, but not limited to, cleaning user input to prevent XSS, as well as preventing SQL Injection by preparing statements with bind variables.

Block large requests and responses: Some attackers may try to overwhelm the API or trigger a buffer overflow vulnerability with large requests. These may be in the form of a large JavaScript Object Notation (JSON) body or unusually large individual JSON parameters within the request. Abnormally large responses may also indicate data theft. Create custom rules to track and block these suspicious requests. A web-application firewall can automatically detect and block this type of input abuse.

Throttling your API: Throttling is a means of controlling or limiting a client’s access to your data. There are two key API throttles that will provide you with additional control and security for your APIs:

  • IP–based throttling: Restrict the number of API calls made by a particular IP address. You could also ensure that your API can only be accessed by a particular set of IP addresses.
  • Rate–limit throttling: Allows API requests to be made until a certain limit has been reached for a specific time period. By utilizing rate–limit throttling within your API, you can ensure the database isn’t overwhelmed by one particular client who may be misusing your interface.

Building tests that don’t represent real functional use: Performing tests without considering how the APIs will be consumed may be quicker in the short term. However, in doing so, you won’t be testing across concerns, which could prevent you from uncovering and debugging potentially serious API issues.

Custom API Rules — Build your own business logic rules for security: For example, a simple protection might be to identify your authentication token (in the HTTP header or in the JSON body) and require it to always be present to block and log any unauthenticated attempts. Another example would be to enforce the Content–Type header to be what is expected for your API (e.g., application/JSON) or block unused or non–public HTTP methods (e.g., PUT and DELETE) to further lock down the API.

Testing APIs in a vacuum: Building API tests can be a bit of a solo act, but once a test is in your workflow, it requires the attention of different teams in your organization. If you set up test failure notifications to go to just you, you’re adding time, effort, and headaches to your workflow.

Keys in Uniform Resource Identifier (URI): Implementing API keys for authentication and authorization is good, but sending the key as part of the URI can lead to compromise. As explained in IETF RFC 6819, it’s safer to send API keys in the message authorization header, which is not logged by network elements. Using the HTTP POST method with payload carrying sensitive information is recommended.

Geofencing: If your API is public, it might make sense to block users from countries you don’t do business with or raise the risk score of entities from those countries.

API fuzzing protection: Attackers may attempt to map and exploit undocumented API features by iterating or fuzzing the endpoints. Install a web-application firewall for profiling and behavior tracking.

L7 DOS protection: Even with rate-limiting, backend services can be exposed to Layer 7 denial-of-service. Customize your firewall to ensure long-running queries get tarpitted and eventually blocked automatically.

Use auditing and logging: Auditing should never be skipped. Logging should be systematic, independent, and resistant to log injection attacks. Auditing helps detect and proactively prevent attacks.

Monitor add–on software carefully: Interfaces allowing third-party apps can expose vulnerabilities. Hackers covet those privileges and will try to exploit them.

Secure the exit gateways: Businesses need to set up checkpoints on the way out of the network. Even if hackers access confidential information, it has value only if they can exfiltrate it.

Stack trace: Returning stack traces can leak information attackers can exploit. Always return minimal, balanced error objects with proper HTTP codes and no stack trace.

Consider adding timestamp in request: Add a timestamp as an HTTP custom header in API requests. The server compares it to the current time and accepts requests only within a short timeframe to prevent replay attacks.

Design Guidelines for Developers

DevOps has simplified resource allocation, but with the pressure to deliver quickly, developers may make mistakes. The following design guidelines can help create secure APIs:

  • Drop Basic Authentication: Avoid sending credentials in plain text; use JWT or OAuth instead.
  • Don’t ship a home–grown solution: Use proven authentication and token-generation methods.
  • Never expose information or URLs: Don’t include sensitive data like API keys in URLs.
  • Implement max retry and jail safety mechanisms: Limit failed login attempts and temporarily block offending IPs.
  • Encrypt everything: Always use HTTPS and encrypt sensitive data in transit and at rest.
  • Limit requests: Use rate-limiting to prevent DoS attacks.
  • Enforce HTTP methods: Each endpoint should support only valid HTTP methods and return 405 for disallowed ones.
  • Validate user–submitted content: Sanitize all inputs to prevent XSS, SQL Injection, and similar attacks.
  • Remove components with vulnerabilities: Regularly update and clean up unused dependencies.
  • Protect sensitive endpoints: Require authentication for all sensitive routes.
  • Avoid using auto–incrementing IDs: Use UUIDs instead to prevent resource enumeration.
  • Apply strict input validation: Use schema validation and parameter whitelisting.
  • Use password hash: Always hash passwords using secure algorithms like bcrypt or PBKDF2.
  • Turn debug mode off: Disable debug mode before deployment to prevent accidental exposure.
  • Logging and monitoring: Log all access attempts and failures for forensic analysis.

API Management Solutions – Why Organizations Need It

According to Gartner, “It is impossible to provide the platform for any digital strategy, build ecosystems, and run an effective API program without full life cycle API management.”

Full life-cycle API management covers planning, design, implementation, testing, publication, operation, consumption, maintenance, versioning, and retirement. Its purpose is to manage APIs from creation to quality control, from access control to quotas and spike arrest, while providing logs, audit trails, and embedded security policies.

Popular tools include Apigee, AWS API Gateway, MuleSoft Anypoint, CA API Management, IBM API Connect, Akana, Postman, Microsoft, Software AG, TIBCO, Axway, Kong, Boomi, and WS02.

As API usage continues to rise, organizations must prioritize security, close vulnerabilities, and adopt best practices. An unsecured API endpoint can become a gateway for attackers, leading to data breaches.

The goal of this article is to help developers understand design principles and security best practices to protect APIs from malicious activity. By applying these practices thoughtfully, businesses can avoid breaches and maximize their potential without compromising security.

Leave a Reply

Your email address will not be published. Required fields are marked *