Blog

API Security: Best Practices and Insights

Milena Zahorska
Milena Zahorska
Quality Assurance Engineer
April 09
10 min
Table of Contents

Security in APIs is very important and involves much more than just the process of logging users in. Of course, authentication (proof of identity) is the foundation, but there are many other methods that help protect data from unauthorized access and attacks.   

Session/token expiration  

Tokens (special “keys” that allow users to log in to the system) are often used in web applications. One of the most common problems is that tokens do not have a specific expiration time. This means that the user can use the application even after the session has ended, which creates a risk if the session is taken over by an unauthorized person.  

How to prevent this? Each token should have a specific expiration time, after which the user will have to log in again. In addition, a token renewal system can be put in place to extend the session, but only if the tokens are properly secured.  

No token cancellation after logout  

Another problem is when a user logs out of the system, but his token remains active. This means that he can still access the application until the token expires, which can take a long time.  

How to prevent this from happening? Once logged out, the token should be invalidated immediately so that it cannot be used again to log in. It is also a good idea for the system to regularly check the validity of the token.  

Checking roles and permissions  

In any web-based application, especially those that provide various resources and functions, it is important that users have access only to those parts of the system to which they are properly authorized. Systems typically rely on user roles that define the scope of their privileges. For example, a user with the “regular” role may only have access to their own data, while a user with the “administrator” role will have access to manage other users’ data. In such a situation, when a user tries to access resources to which he or she does not have permission, the API should check that user’s role and respond accordingly.  

In most cases, if the user doesn’t have sufficient permissions to perform a certain action, the API will return a 403 (Forbidden – No permission) error. For example, when a user with the role “ordinary” tries to access the admin panel, the API should respond with a 403 code, informing the user that he or she does not have the appropriate permissions for this operation.  

In some situations, it may be more advisable to return a 404 (Resource Not Found) error instead of returning a 403 (No Permission) error for increased security. Such a procedure is intended to hide the structure of the system from unauthorized users and prevent the existence of sensitive resources from being revealed. An example would be when a user from outside the organization tries to access a resource that is restricted to its members, such as an application repository. Then, instead of informing that he lacks the appropriate permissions, the API can simply state that the resource does not exist, effectively protecting its existence.  

Checking roles and permissions  

Changing error messages  

Changing the API’s error messages is a key element in improving system security, as it prevents the disclosure of detailed information that could be exploited by attackers. Instead of providing detailed messages, such as “bad email” or “bad password,” it is worth using a generic message, such as “login credentials invalid.” This kind of approach makes it difficult for attackers to launch effective brute force attacks, because they don’t find out which part of the login data is wrong.  

In addition, this method of communication prevents system exploration by potential attackers, who could try to discover system structure and available resources based on detailed errors. A generic error message also reduces the risk of social engineering attacks, such as phishing, because the attacker does not obtain information that can be used to manipulate users. In addition, the use of generic messages helps protect users’ privacy because it makes it impossible to see which logins exist on the system.  

As a result, changing error messages to generic responses improves the security of the entire system, makes it harder for attackers to gather information about the system, and significantly increases the API’s resistance to various types of attacks.  

Rate Limiting – Limiting the number of requests  

One of the most important aspects of defense against attacks is rate limiting, which is limiting the number of requests that can be made at a given time from a single source (e.g., an IP address). Without this mechanism, an API can be vulnerable to brute force attacks, in which an attacker tries to guess login credentials by continuously sending requests.  

Example: If the API does not have limits on the number of login attempts, an attacker can try different combinations of passwords and logins indefinitely until he succeeds in breaking the security.  

A safe practice in this situation is to use a rate-limiting mechanism, such as limiting the number of login attempts per minute from a single IP address, is an effective defense against brute force attacks. It’s also a good idea to add a mechanism to block an account after several failed login attempts, and use CAPTCHAs when unusual activity is detected.  

API Vulnerability Testing  

Vulnerability testing involves checking whether the system is immune to the actions of people who try to cheat or take control of it. Even if the user is not familiar with the technical details, it is useful to know what such tests protect against.  

API Vulnerability Testing  

SQL Injection is an attempt to “fool” a database by entering unusual data that can extract or alter information that someone should not have access to. Imagine a login form – if the system doesn’t properly check what you enter there, someone can enter special code instead of data and get inside the system.  

XSS (Cross-Site Scripting) involves inserting malicious code (e.g., JavaScript) that can display false messages or steal data – for example, your login credentials. Such attacks are particularly dangerous in web applications. 

A safe practice in this situation is to use a rate-limiting mechanism, such as limiting the number of login attempts per minute from a single IP address, is an effective defense against brute force attacks. It’s also a good idea to add a mechanism to block an account after several failed login attempts, and use CAPTCHAs when unusual activity is detected.  

CSRF (Cross-Site Request Forgery) is an attack that takes advantage of the fact that you are logged in. Someone can impersonate you and perform an operation without your knowledge – such as changing your data on the system. Adequate security ensures that such an operation is blocked.  

RCE (Remote Code Execution) is a very dangerous vulnerability – if the system is not well protected, someone can send a file or data that will allow them to take full control of the server. It’s like an enemy entering a building through a hole in the wall and having access to everything.  

By regularly testing these vulnerabilities, you can secure your API against the most dangerous types of attacks and significantly increase the security level of your system.  

Summary: Why is Comprehensive API Security Testing vital? 

API security testing is a complex process that involves not only testing the login and authentication itself, but also verifying the entire protection structure against attacks. It is important to conduct regular tests that cover all aspects of security – from access control to protection against network attacks. 

TIP: The following checklist can be helpful in testing API security:  

Checklist: API Security Testing  

Authentication and authorization:  

  • Login testing: Ensure that users must provide valid login credentials (username/password). 
  • Session testing: Verify that user sessions have a certain lifetime and expire after a certain period. 
  • Testing token refresh: Verify that the system correctly handles token refreshes when they expire. 
  • Testing logout: Ensure that after logout, tokens are immediately invalidated and API access is blocked.  
  • Testing post-logout access: Try executing queries after logout and verify that the API blocks access.  

Roles and permissions:  

  • Testing user roles: Make sure that users with different roles only have access to the appropriate resources (e.g., a regular user does not have access to the admin panel).  
  • Testing 403 and 404 errors: Verify that the API returns a 403 (Forbidden) or 404 (Not Found) error when attempting to access resources to which the user does not have permission.  
  • Testing inheritance of permissions: Verify that the system correctly inherits permissions from parent roles and does not assign unnecessary permissions.  

Responding to errors:  

  • Testing error detail hiding: Verify that the API does not reveal error details that can help detect system structure.  
  • Testing error messages: Make sure the API returns generic error messages, such as “login credentials invalid” instead of “bad email” or “bad password.”  

Rate Limiting and Attack Protection:  

  • Rate limiting testing: Verify that the API limits the number of requests from the same source within a certain period of time (e.g., login attempts within one minute).  
  • Brute force attack testing: Ensure that the API blocks an excessive number of failed login attempts.  

 Verification of resources and queries:  

  • Testing HTTP requests: Verify that the API correctly handles various HTTP methods (GET, POST, PUT, DELETE), and also checks authorization before performing operations.  
  • Testing queries to non-existent resources: Ensure that queries to non-existent resources return the appropriate error (404).  
  • Testing unauthorized access: Try to access resources without proper permissions and make sure the API returns a corresponding error.  

Vulnerability testing:  

  • SQL Injection Testing: Verify that the API is resistant to SQL Injection attacks by properly validating and filtering input data.  
  •  XSS (Cross-Site Scripting) Testing: Ensure that the API prevents malicious JavaScript code from being injected into input data.  
  • CSRF (Cross-Site Request Forgery) Testing: Ensure that the API employs appropriate safeguards against CSRF attacks (e.g., CSRF tokens).  
  •  RCE (Remote Code Execution) Testing: Verify that the API is vulnerable to attacks that allow malicious code to be executed remotely.  

Interested? Check out the next parts in this series:

What The API Says & What It Shouldn’t – The Hidden Dangers of Excess Data

Improve Your API: A Comprehensive Approach To Input Validation

Milena Zahorska
Milena Zahorska
Quality Assurance Engineer
  • follow the expert:

Testimonials

What our partners say about us

Hicron’s contributions have been vital in making our product ready for commercialization. Their commitment to excellence, innovative solutions, and flexible approach were key factors in our successful collaboration.
I wholeheartedly recommend Hicron to any organization seeking a strategic long-term partnership, reliable and skilled partner for their technological needs.

tantum sana logo transparent
Günther Kalka
Managing Director, tantum sana GmbH

After carefully evaluating suppliers, we decided to try a new approach and start working with a near-shore software house. Cooperation with Hicron Software House was something different, and it turned out to be a great success that brought added value to our company.

With HICRON’s creative ideas and fresh perspective, we reached a new level of our core platform and achieved our business goals.

Many thanks for what you did so far; we are looking forward to more in future!

hdi logo
Jan-Henrik Schulze
Head of Industrial Lines Development at HDI Group

Hicron is a partner who has provided excellent software development services. Their talented software engineers have a strong focus on collaboration and quality. They have helped us in achieving our goals across our cloud platforms at a good pace, without compromising on the quality of our services. Our partnership is professional and solution-focused!

NBS logo
Phil Scott
Director of Software Delivery at NBS

The IT system supporting the work of retail outlets is the foundation of our business. The ability to optimize and adapt it to the needs of all entities in the PSA Group is of strategic importance and we consider it a step into the future. This project is a huge challenge: not only for us in terms of organization, but also for our partners – including Hicron – in terms of adapting the system to the needs and business models of PSA. Cooperation with Hicron consultants, taking into account their competences in the field of programming and processes specific to the automotive sector, gave us many reasons to be satisfied.

 

PSA Group - Wikipedia
Peter Windhöfel
IT Director At PSA Group Germany

Get in touch

Say Hi!cron

    Message sent, thank you!
    We will reply as quickly as possible.

    By submitting this form I agree with   Privacy Policy

    This site uses cookies. By continuing to use this website, you agree to our Privacy Policy.

    OK, I agree