
SB Karunarathne
13 October 2023
|15 min read
Nowadays, REST APIs are widely used for building APIs due to their many benefits such as simplicity, scalability, ease of use, and statelessness. REST APIs are commonly implemented using HTTP, making them accessible through standard HTTP requests and responses.
In general, when we build an API, several factors need to be considerd. Usage, scalability, performance, versioning, and security are some of them. Among them, securing APIs is crucial in API access management. A secured API not only prevents unauthorized access but also offers numerous other advantages such as integrity maintenance and regulatory compliance. As technology advances, API developers should continually strive to fortify their APIs against potential threats from unintended sources.
When we consider API security, it’s important to manage it at different layers such as the transport layer and application layer. As the REST APIs are used using the HTTP that operates at the transport layer (OSI Model - Layer 4), we can enhance the security of the transport layer by using HTTPS. HTTPS helps to have end-to-end encryption in the wire when the API requests and response are transmitted over the network. On the other hand, when dealing with the application layer security, the developers have to think about authentication, authorization, protection against malicious attacks, rate limiting, as well as service availability in the face of attaks such as DoS and DDoS. The main focus of this article is to give a basic understanding about securing the APIs and how Authentication and Authorization can help to make this successful.
Authentication is the process of verifying the identities of users or clients based on a particular security implementation. To prove their identity, users or clients must provide credentials, which the security system then evaluates to determine their validity. Primarily, the authentication process allows us to accomplish the following:
User should have valid credentials and proper permission to access the resources (APIs).
With the credentials provided by the user/client, the identity can be revealed and used for personalized, secured access to the APIs.
Based on the information provided by the user, the user's activity can be logged and used for audit processes later.
The authentication process can be implemented in different ways and it can be varied based on the requirement. Let’s explore some of the widely used implementations!
This is a common approach used in REST where the client sends the API Key along with all the requests (most often the key is sent as a header or a query parameter, which is not safe) and the server validates the API Key and checks whether the request can be authorized. In this approach, usually the API provider generates a unique API key for each client that grants access to the APIs. Following are some of the factors we have to consider when the API Key authentication is used for REST APIs:
API Keys should not be stored in an easily accessible manner. Instead of keeping the API Key with the source code, use a secure storage solution and retrieve it when the program is executed. API Keys should also have their own scope to prevent unauthorized API access.
API Keys should not be long-lasting. They should be periodically rotated and set to expire after a certain period.
Providing HTTPS support ensures end-to-end encryption between the client and the server, securing API access.
Limiting the number of requests coming to the server ensures fair usage and helps prevent attacks such as DoS and brute force.
APIs should be monitored to identify potential attacks. Request patterns and metrics should be tracked and controlled to maintain system health. API access should be logged to detect exceptions or misuse attempts.

With this approach, the username and password will be concatenated (username:password) and encoded with base64 and sent along with each API request. The credentials sent will be validated against the credentials that are saved in the server to grant access. Usually, the ‘Authorization’ header is used to send the credentials where the encoded credentials are prefixed with the word ‘Basic‘, e.g., Basic bXl1c2VxOm15dGFzc3dvrmQ=. There are certain factors to consider when using this approach to authenticate the APIs:
As credentials are sent in plain text, it is insecure if end-to-end encryption at the transport layer is not implemented.
Passwords should be hashed and salted before storing in the database to prevent data breaches.
Rate limiting should be implemented to prevent brute force attacks. DoS/DDoS attacks can make the system unavailable.

In this approach, the client will receive a token, e.g., OAuth2 token and JWT, from the authentication process. That token will be sent to the server along with each request. Usually, the token is sent with the ‘Authorization’ header and the token will be prefixed by ‘Bearer ‘. The server checks the token validity and provides the access to the resources if the token is valid. Under Token Authentication, we will briefly examine OAuth2 and JWT authentication.
This is a widely used approach for authentication and authorization of REST APIs. With this method, the third-party application can access data on behalf of users without revealing the credentials. OAuth2 is a result of a collaboration of multiple components/parties:
The application that consumes the service of the OAuth2 access token. The client could typically be a web application, mobile application, or any other type of application.
The server that contains the resources (in our case the APIs) that the client wants to access.
The server that helps to authenticate the user and generate the access token for the client. User consent and token validation are part of this process.
The user who owns the data and resources that the client wants to access.
As discussed above, the authentication server generates the access token and provides it to the client. The client uses the access token in order to access the APIs in the resource server. Usually the tokens are short lived and can have different scopes as per the client needs. In OAuth 2, the ‘grant type’ is used to address different use cases:
This is a two-step process. The client sends the authorization code and exchanges it for an access token. This is more suitable for web applications.
The client provides its credentials and receives an access token. This is commonly used for server-to-server communication.
The access token is provided directly without an authorization code. This is suitable for client applications like web apps.
The client provides the username and password and receives an access token. This is usually used in trusted environments but is not recommended.
This grant type allows obtaining a new access token (e.g., after expiration) without any user interaction. It enhances token security by minimizing the use of long-lived tokens.
With the collaboration of the above components, let’s discuss how we can retrieve an access token using OAuth2 using the ‘Authorization Code’ grant type. Please note that it is nearly similar to other grant types (of course there are some slight differences in each scenario):
The client initiates the OAuth2 flow by redirecting the user to the authorization server for authentication.
The user logs in and grants the requested permissions (scopes). If successful, the authorization server generates an authorization code and returns it to the client.
The client exchanges the authorization code or, in some flows, directly receives the access token from the authorization server.
The client includes the obtained access token in API requests to access the protected resources.

OAuth2 is widely used and secure and suitable for various use cases. We need to have a careful implementation in order to avoid security vulnerabilities. We need to have a proper attention on token management, token expiration, and user consent for a proper OAuth2 implementation.
JSON Web Token (JWT) is a compact, self contained token. This token is used for implementing the authentication as well as authorization in web applications. A Typical JWT consists of three parts:
Usually the header contains the token type, algorithm, and other useful information.
Generally, the payload contains the subject (usually the username), token issued time, token expiration time, and any other useful information like permissions.
This section is used to verify the sender of the JWT and to ensure the message has not been altered in transit.
To create the token, we need to follow the following steps (usually we can use third-party libraries to generate the tokens by providing the required information):
Prepare the header component.
Prepare the payload component.
Prepare the signature component.
Encode the header using a base64 encoder.
Encode the payload using a base64 encoder.
Concatenate the encoded header and payload with a '.' separator.
Sign the concatenated string using a secret and the algorithm specified in the header.
Concatenate the header, payload, and signature using '.' to create the final JWT token.
After the token is created, we can use it for authenticating the APIs. Usually the token is sent along with the ‘Authorization’ header with the token prefixed with ‘Bearer ‘. The most important things to remember when using JWT tokens are:
After JWT tokens are used, they should be properly disposed. If the token is not expired, it could still be used by someone else.
JWT tokens should be short-lived to minimize the risk of misuse.
Implement a refresh token mechanism to handle short-lived JWT tokens while maintaining a good user experience.

Even though token based authentications like OAuth2 and JWT are good authentication mechanisms, there are facts that we need to take care when we use it. Here are some points that need to be taken care of.
If the token is not properly protected by the client, it can be used by external parties.
Having long-lived tokens is unsafe as they can be used by others. Short-lived tokens improve security but may affect user experience; this can be mitigated with a refresh token mechanism.
Tokens should be properly disposed after use. Otherwise, they may be exploited by external parties, posing a security risk.
Improperly stored tokens can be vulnerable to attacks such as cross-site scripting (XSS).
Minimize payload size to save bandwidth and avoid storing sensitive information, as it can be easily read by others.
Tokens should be properly validated for tampering, and expiration should be checked to prevent unauthorized access to resources.
HMAC involves hashing the request data and using a shared secret key to create a signature. The server verifies the signature to authenticate the request.
This authentication approach is somewhat similar to Basic Authentication but is more secure. It uses a challenge-response mechanism with hashing to authenticate the request.
Apart from the above-mentioned authentication types, there are other implementations like biometric authentication and certificate-based authentication. You can also implement a custom authentication mechanism by combining one or more of the above types with additional steps. To strengthen security, it is recommended to introduce a secondary verification method using multi-factor authentication (MFA).
Authentication alone cannot fully secure an application. For example, users with generic permissions should not access admin-level features like user management. Authorization addresses this by granting or denying access to specific resources, data, or actions based on the permissions or roles assigned during authentication. Some of the benefits and purposes of authorization include managing access control, ensuring security, and protecting sensitive resources.
As we discussed above, authorization can be split into two types:
Let’s discuss further on these to get more understanding how each of them handle the authorization for the logged in user!
In Role-Based Authorization (RBA), access permissions are granted to a role rather than directly to a user/client. Multiple roles with different permission levels can exist, and a user may be assigned one or more roles. Once authenticated, permissions are retrieved based on the assigned roles. RBA simplifies access control and role management, allowing updates at the role level to control access for multiple users at once.
In Attribute-Based Authorization (ABA), access permissions are granted based on attributes associated with the user, the resources or actions being accessed, and the context of the request. ABA provides fine-grained access control compared to role-based authorization.
With the advancement of technology, new mechanisms for Authentication and Authorization may emerge, including improvements in multi-factor authentication, biometrics, and areas not yet imagined. As technologies, such as quantum computing, continue to develop, new types of threats may arise. Applications should be adequately protected, and proactive measures should be taken to address potential future challenges.
API Design-First (also known as API-first design or API-driven development) is the approach of designing the API specification before writing the implementation code. Adhering to API-driven development provides advantages such as better maintainability, more robust API design, and improved enforcement of authentication and authorization strategies.
APIs that require authentication and authorization can be identified in advance. Some APIs may be public, while others may be restricted to users with admin privileges. Defining these contracts helps ensure solid implementation and validates adherence to specifications.
APIs are subject to regulatory requirements such as GDPR and HIPAA. Starting with a security-focused design ensures compliance with security and privacy standards.
API design-first includes API mocking and testing, which allows developers to verify that proper authentication and authorization mechanisms are in place.
There are different tools that can be used for implementing the API Contract (API Specification) in API Design-First approach for authentication and authorization. Xapi is such a great tool fully compliant with Open API Specification 3.1.0 and can be used to achieve design specification and testing.
Authentication and Authorization are among the most critical areas to address when safeguarding data manipulated through APIs. Protection for the APIs and data should be continuously updated to defend against the emerging threats that arise daily.
Share Article
In today's rapidly evolving digital landscape, organizations are constantly striving to accelerate development, enhance their offerings, and maintain a competitive edge. A critical, yet often overlooked, aspect of achieving these goals lies in the ability to truly see and understand digital assets.

Prabath Ariyarathna
13 February 2026
Read More
We're thrilled to unveil our latest Xapi platform update, bringing a more intuitive API design experience, tooling enhancements, and a smarter way to govern externally designed APIs. These new capabilities make API design and governance more accessible, more powerful, and more flexible than ever before.

Shamali Sathindra
8 April 2025
Read More
Every organization wants well-designed APIs, but the key is turning business needs into carefully crafted APIs that perfectly match their main business objectives.

Prabath Ariyarathna
17 February 2025
Read More