API Config Auth Tutorial Copie
API Config Auth Tutorial Copie
Contents
1 Introduction 3
2 Configuration 3
3 Rate Limit 3
4 Authentication 4
5 JWT 4
5.1 JWT authorization workflow: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
* https://intra.forge.epita.fr
2
1 Introduction
To use an API, developers need to configure and authenticate it properly. Configuration involves setting
up the API to work with specific application or system, including defining the appropriate endpoints,
parameters, and data formats.
Authentication, on the other hand, is the process of verifying the identity of the user or application
attempting to access the API and ensuring that they have the appropriate permissions to access the
requested resources.
The security and functionality of an API rely heavily on proper configuration and authentication. An
API configured inadequately can be vulnerable to attacks, and insufficient authentication can result
into data breaches. Therefore, it is essential to understand the best practices for configuring and
authenticating APIs to ensure that they are both secure and efficient.
2 Configuration
Configuring an API is the action to define allowed actions that a client can or should do in order to
communicate with it. It involves defining appropriate endpoints and their parameters.
API configuration may also involve setting up authentication protocols, but this part will be explained
later.
One popular way to configure an API is to set rate limits.
3 Rate Limit
In programming, rate limiting is used to restrict the number of requests that a client can make to a
specific endpoint on a server.
It is primarily used for safety considerations, and to prevent DoS attacks and web scraping
It may be implemented in several ways. The API configuration may allow a certain amount of requests
within a given time window (for instance one request per second), or it may allow a certain amount of
request per user, IP address…
The API will track the number of requests made, and if the defined limit is exceeded, it will likely send
a 429 : Too many requests HTTP error.
Some headers are defined in order to track some data about rate limits. They can be retrieved from
the response headers.
• X-RateLimit-Limit: maximum number of requests for the client in the time window.
• X-RateLimit-Remaining: remaining number of requests in the current window.
• X-RateLimit-Reset: an Unix timestamp that indicates the time at which the rate limit will reset.
It allows the client to ensure that they will not encounter a 429 : Too many request error while mak-
ing request to an API.
Assuming that the following endpoint is rate limited, you should retrieve ratelimit information this way:
3
const res = await axios.get(`http://localhost:3000/`);
console.log(res.headers["x-ratelimit-limit"]);
console.log(res.headers["x-ratelimit-remaining"]);
console.log(res.headers["x-ratelimit-reset"]); // milliseconds
console.log(res.headers["x-ratelimit-reset"] * 1000 - Date.now()); // Displays duration␣
,→before next request's counter reset.
4 Authentication
Authentication is the process of validating the identity of a client or application that is attempting to
make a connection to an API.
This process ensures that resources are only accessible to authorized users.
It can be implemented in several ways. One of the most common way is to use API keys. They are
unique identifiers bound to a given user. They are passed as parameters or as part of the headers in
API requests.
One way to create such keys is to use JSON Web Token objects.
5 JWT
A JWT (JSON Web Token) is a type of token that is used to securely transmit information between two
parties (a client and a server). It is an open standard (RFC 7519) that defines a compact and self-
contained way of transmitting data between parties as a JSON object.
JWT tokens are commonly used in authentication and authorization processes, such as in web applica-
tions and APIs. Once a user logs in and is authenticated, a JWT token is generated and sent back to the
user. This token is then included in subsequent requests to authenticate the user, and grant access to
authorized resources.
JWTs are made up of three distinct parts (encoded in base64), each separated by dots (“.”):
• Header: This contains information about the type of token and the hashing algorithm used to
sign it.
• Payload: This contains the data or information that is being transmitted between parties. It can
include information such as the user ID, user role, and any other relevant information.
• Signature: This is a hash of the header and payload, signed using a secret key. The signature is
used to verify that the token was not tampered with during transmission.
For example, with this payload:
{
"login": "xavier.login",
"UID": "25000",
"campus": "Kremlin-Bicêtre"
}
4
We can generate this JWT using the secret key "very secret key":
The red part represents the header part, the purple one represents payload data and the blue one
represents the verify signature.
There are many ways to include the generated token for following request. You can pass them in the
HTTP authorization headers, or put them in the cookies.
• The user logs in. An authentication request is sent to the JWT issuer in order to obtain a JWT token.
• The JWT issuer sends back the JSON token to the user. Users’ credentials need to be valid, oth-
erwise an error response would be thrown.
• While sending a request, the user sends the received token in the HTTP authorization request.
• While receiving the token, the server checks the validity of the token.
– If it is invalid, an error response will be sent.
– Otherwise, the API gateway provides access to protected resources.
5
Going further...
If you want to learn more information about JWT workflow, you should look at this resource.
// Returns a valid JWT and a HTTP 200 Status Code if credentials are valid.
// Returns an HTTP 401 (Unauthorized) Status Code otherwise.
const res = await axios.post(`http://localhost:3000/login`, {
username: "xavier.login",
password: "1234",
});
// If the response has been successfully received, the JWT can be retrieved from the response␣
,→data.
// Once recovered, it can be provided to the authorization header.
await axios.get(`http://localhost:3000/secret`, {
headers: {
Authorization: `Bearer ${ res.data.jwt}`,
},
}); // { message : "Access granted" }
Going further...
If you want to learn more about authentication processes, you should check what OAuth , Cross
Origin Resource Sharing and Same Origin Policy are.