API Security

In our ever-evolving digital world, security is paramount. As developers, we are the gatekeepers of this digital world, where APIs (Application Programming Interfaces) serve as the bridge between applications, enabling seamless communication. Picture this: Imagine someone is hearing our every conversation; that's what a security breach in the digital realm feels like. So, it's our duty as developers to ensure the utmost security in data transfer. In this blog, we'll explore the world of API security, best practices, common vulnerabilities and the methods we can employ to protect our digital domain.

Table of contents:

  1. Common security vulnerabilities
  2. Authentication vs Authorization
  3. Methods of authentication
    1. Basic auth
    2. Token based authentication (JWT)
    3. API key
    4. OAUTH
  4. CORS (Cross Origin Resource Sharing)
  5. Rate limit
  6. Other techniques
  7. Testing and Auditing

Common security vulnerabilities

SQL injection

Imagine a hacker sending the malicious code through an innocent-looking input field. This is SQL injection, a vulnerability that can lead to unauthorized access, data manipulation, and even bring down the server.

To shield against this threat, we need robust input validation, sanitization, and the implementation of parameterized queries instead of direct ones.

Cross-Site Request Forgery (CSRF):

CSRF tricks users into unwittingly performing actions they never intended. These attacks can lead to unauthorized API actions carried out on behalf of the users.

We can prevent CSRF with the implementation of CSRF tokens in web forms and by enforcing the "SameSite" attribute in cookies.

Cross-Site Scripting (XSS):

Picture a scenario where a cyber trickster injects the malicious scripts into web pages, which then execute when users interact with the website. This is the Cross-Site Scripting (XSS) attack.

Guarding against XSS requires proper input validation, sanitization, and the use of security measures like Content Security Policy (CSP).

Authentication vs Authorization:

Authentication verifies the identity of users, like a digital bouncer asking, "Who are you?" It's the process of confirming their credentials, such as usernames and passwords. Authorization, on the other hand, follows authentication and asks, "Now that we know who you are, what are you allowed to do?". It's like the backstage pass, ensuring the right folks access the VIP area of the server.

Methods of authentication:

Basic Authentication

Basic, yet straightforward. It uses usernames and passwords sent either in the URL or as base64-encoded credentials in headers.

Advantages:

  1. Simple and easy to use and integrate
  2. Time efficient
  3. No dependencies

Disadvantages:

  1. Less secure
  2. Username and password can be decoded easily
  3. No session management
Token based authentication (JWT):

Token-Based Authentication, employing JSON Web Tokens (JWTs), is a robust and widely adopted method. JWTs encode user information, along with timestamps, and are sent as Bearer tokens in headers. They offer strong security, versatility, and can handle sessions efficiently.

Advantages:

  1. Highly secured using signed token
  2. Optional encryption to protect the encoded data
  3. Authorization and Role based access
  4. Session management
  5. Easy to implement and use
  6. Scalable
  7. Easy to expire token and refresh token

Disadvantages:

  1. Token can be larger if the data encoded is large
  2. Possibility for attacks since it is stored in client side
  3. Lack of logout functionality
OAUTH

OAuth, short for Open Authorization, is the gold standard for authentication. It's widely used for granting access to third-party applications, enabling Single Sign-On (SSO), and facilitating social login through platforms like Google, Facebook, and GitHub. Although it offers robust security, OAuth can be complex to implement and may require careful access scoping.

Advantages:

  1. Highly secured
  2. User friendly
  3. Highly scalable
  4. Granular access control
  5. SSO
  6. Access revocation

Disadvantages:

  1. Complex to implement
  2. Access scoping is difficult
  3. Lack of native logout functionality

CORS (Cross Origin Resource Sharing):

Imagine CORS as a virtual velvet rope that web browsers use to enforce safe cross-origin requests. It ensures that the server responds only to authorized clients, preventing the API from being integrated into unintended web applications. However, it's important to note that implementing CORS on the server does not block requests sent from unauthorized servers.

Rate limit:

While rate limiting may not be a directly related to security, it plays a pivotal role in safeguarding the API against various threats, including:

  1. DDoS attack (Distributed Denial of Service): Attackers flood the server with a high volume of requests in a short period, causing it to crash or become unresponsive.
  2. Brute force attack: Attackers attempt to gain unauthorized access by sending a large number of random username and password combinations.
  3. Dictionary attack: Similar to brute force attacks, but hackers use predefined sets of words as passwords instead of random combinations.
  4. Resource exhaustion: Attackers can deplete server resources like CPU and RAM with tons of requests, leading to server crash.
  5. Cost escalation: Making excessive requests can drive up server costs, especially if the API relies on third-party services.
  6. API request exhaustion: Attackers may intentionally use up the API's request limit, which will affect the limit of the API requests if the third party API is used.
  7. Data harvesting: Malicious entities may use APIs to harvest data.

Limiting the number of requests an API can handle within a specific time frame is crucial. For example, you might restrict individual users to making only ten requests per minute.

Other Techniques:

In certain scenarios, you may need to enforce additional security measures, such as:

  1. VPN (Virtual Private Network):Restricting API access to users connected to a VPN, creating a closed circle of trusted individuals.
  2. AWS Region Restrictions:Making the application accessible only from specific regions in cloud providers like AWS.
  3. IP Whitelisting:Allowing API access only to known and trusted IP addresses.
  4. Geolocation Filtering:Configuring the application to respond only to requests originating from specific regions.

Testing and Auditing:

Testing:

Building a robust fortress is one thing, but fortifying it is another. To ensure security, we must conduct various tests, including:

  1. Penetration Testing:Simulating real-world attacks to identify vulnerabilities.
  2. Vulnerability Scanning:Employing automated tools to regularly scan for known vulnerabilities and misconfigurations.
  3. Load Testing:Load testing is not focused on security, it can indirectly reveal some security-related issues.
  4. Data Validation Testing: Verifying that the API correctly validates and sanitizes data.
    Automating unit tests and integration tests at regular intervals helps ensure that the server remains impervious to threats.
  5. Auditing:Regular audits serve as guardians against misconfigurations and policy violations. Code reviews are essential to ensure the code adheres to best practices. Utilizing tools like SonarCloud for code reviews can enhance the codebase's security. Frequent analysis of application logs offers insights into usage patterns and potential security incidents. Creating dashboards to monitor system health, resource usage, and generating periodic reports provides a comprehensive view of the security landscape.

In conclusion, securing the API is an ongoing journey. Regular audits, compliance checks, and strict adherence to security policies are the allies in this digital realm. With these safeguards in place, API becomes an impregnable fortress, resistant to all but the most determined attackers.

Sathyanarayanan Dhanuskodi

Software Developer

Published Date: 14-Mar-2024
Last updated Date: 14-Mar-2024