CORS: Concept, Solution and Risks in REST API with API Key
Origin of CORS Error
CORS, an acronym for Cross-Origin Resource Sharing, is a mechanism implemented in web browsers to allow the resources of a web page to be requested from a domain other than the one that served the first page. This mechanism is designed to protect the user from malicious attacks that could compromise their data through cross-site requests.
The CORS error arises when a web application tries to make a request to an API that is hosted on a different domain than the application. For example, if your application on https://miapp.com tries to access an API on https://api.externo.com, the browser will block the request due to its same origin policy, unless the external API has Properly configured CORS headers to allow requests from your domain.
CORS Error Example
Without proper CORS configuration, an AJAX request from https://miapp.com to https://api.externo.com would fail:
fetch("https://api.externo.com/datos")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error al realizar la petición:', error));
The browser will display an error similar to:
Access to fetch at 'https://api.externo.com/datos' from origin 'https://miapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Solution: Enable Origin Domain
To resolve the CORS error, the API server must include the Access-Control-Allow-Origin header in its response, specifying the domains that are allowed to access the resources. This can be set generally or specifically for certain domains.
Risks When Using API Key for Authorization
Using API Keys as an authorization method in conjunction with CORS poses a significant risk. When making requests directly from the FrontEnd, the API key can be exposed through the browser's source code or development tools, putting API security and data integrity at risk.
API Key Exposure Example
fetch("https://api.externo.com/datos?apiKey=MI_API_KEY_SECRETA")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
In this case, anyone with access to the browser could easily see the API key used in the request.
Recommendation: Make Connections from the BackEnd
To mitigate security risks associated with exposing API keys and other sensitive data, it is recommended to make requests to external APIs from the BackEnd of the application. This way, the authorization logic and handling of API keys remain hidden and secure on the server.
Example of Request from the BackEnd
const fetch = require('node-fetch');
// Función para realizar la solicitud a la API externa desde el servidor
function obtenerDatosDesdeAPI() {
const url = "https://api.externo.com/datos?apiKey=MI_API_KEY_SECRETA";
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error al realizar la petición:', error));
}
By making requests through the server, you preserve the security of sensitive information and avoid the risk of exposing sensitive data to the client.
In conclusion, although CORS is an effective solution for enabling cross-origin requests, it is crucial to handle the security of API keys and other sensitive data carefully, preferring to make sensitive requests from the server to ensure the security and integrity of the application and its users.
If you also want to make requests from your FrontEnd, contact us at success@icommkt.com, and send us the domain from which the requests will be made
Updated on: 04/29/2024
Thank you!