Authentication overview
Mercadolibre's API platform secures access primarily through the OAuth 2.0 framework. This industry-standard protocol enables third-party applications to obtain limited access to user accounts on an HTTP service, such as Mercadolibre, without exposing the user's login credentials. Instead, applications are granted an access token, which serves as a credential to access protected resources on behalf of the user.
The core principle behind Mercadolibre's authentication system is delegated authorization. When a user grants permission to an application, Mercadolibre issues an access token. This token represents the specific permissions granted by the user and has a limited lifespan. For continued access, a refresh token is typically provided, allowing the application to obtain new access tokens without requiring the user to re-authorize.
This approach is critical for maintaining security and privacy across the Mercadolibre ecosystem, which includes the main marketplace, Mercado Pago for payments, and Mercado Envíos for logistics. Developers integrating with Mercadolibre's APIs for tasks such as managing listings, processing payments, or retrieving order information must implement the OAuth 2.0 flow correctly to ensure secure and authorized operations.
Mercadolibre provides a sandbox environment for developers to test their integrations thoroughly before deploying to production. This allows for validation of authentication flows, API calls, and error handling without affecting live user data or transactions. The Mercadolibre developer documentation offers detailed guides and examples for setting up and testing authentication.
Supported authentication methods
Mercadolibre primarily supports OAuth 2.0 with the Authorization Code Grant flow. This is the recommended and most secure method for applications that can securely store a client secret, typically server-side applications.
| Method | When to Use | Security Level |
|---|---|---|
| OAuth 2.0 (Authorization Code Grant) | Server-side web applications, mobile apps, and single-page applications (SPAs) that require user authorization and can securely store a client secret. | High: Requires secure client secret storage, redirects users, and involves multiple steps to prevent token interception. |
| OAuth 2.0 (Client Credentials Grant) | For applications that need to access Mercadolibre's own resources, not on behalf of a user. Less common for public integrations. | Moderate: Suitable for machine-to-machine communication where no user context is involved. |
The Authorization Code Grant flow involves several steps:
- Authorization Request: Your application redirects the user to Mercadolibre's authorization URL, requesting specific permissions (scopes).
- User Consent: The user logs into Mercadolibre and grants or denies the requested permissions.
- Authorization Code: If consent is given, Mercadolibre redirects the user back to your application's predefined redirect URI, including an authorization code.
- Token Exchange: Your application exchanges this authorization code for an access token and a refresh token by making a server-to-server request to Mercadolibre's token endpoint, using your client ID and client secret.
- API Access: The access token is then used in subsequent API requests to access protected resources on behalf of the user.
For detailed information on implementing the Authorization Code Grant flow, consult the Mercadolibre OAuth 2.0 documentation.
Getting your credentials
To begin integrating with Mercadolibre's APIs, you must register your application and obtain your unique credentials. This process typically involves the following steps:
-
Create a Developer Account: If you don't already have one, register for a Mercadolibre developer account on the Mercadolibre Developers site.
-
Register Your Application: Navigate to the applications management section within your developer account. You will need to provide details about your application, such as:
- Application Name: A descriptive name for your application.
- Application Type: Specify if it's a web application, mobile app, etc.
- Redirect URI(s): This is a crucial step. You must provide the exact URL(s) where Mercadolibre will redirect the user after they grant authorization. These URIs must be secure (HTTPS) and should be under your control. Incorrectly configured redirect URIs are a common source of authentication errors.
- Scopes: Define the specific permissions your application will request from users (e.g., read user information, list items, manage orders).
-
Obtain Client ID and Client Secret: Upon successful registration, Mercadolibre will assign your application a unique
client_idand aclient_secret. Theclient_idis public, used to identify your application during the authorization request. Theclient_secretis confidential and must be kept secure, as it is used to authenticate your application when exchanging the authorization code for an access token. -
Note Down Credentials: Store your
client_idandclient_secretsecurely. Theclient_secretshould never be exposed in client-side code (e.g., JavaScript in a browser).
Mercadolibre provides a sandbox environment where you can obtain separate credentials for testing purposes. It is highly recommended to develop and test your integration in the sandbox before moving to production credentials.
Authenticated request example
After successfully completing the OAuth 2.0 flow and obtaining an access_token, you can use it to make authenticated requests to Mercadolibre's APIs. The access_token is typically included in the Authorization header of your HTTP requests as a Bearer token.
Here's an example of how to make an authenticated GET request to retrieve user information using Python:
import requests
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN" # Replace with your actual access token
USER_ID = "me" # Or a specific user ID
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
api_url = f"https://api.mercadolibre.com/users/{USER_ID}"
try:
response = requests.get(api_url, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
user_data = response.json()
print("User Data:")
print(user_data)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except Exception as err:
print(f"Other error occurred: {err}")
In this example:
ACCESS_TOKENis the valid access token obtained through the OAuth 2.0 flow.- The
Authorization: Bearer YOUR_ACCESS_TOKENheader is essential for authenticating the request. - The request is made to
https://api.mercadolibre.com/users/me, which is an endpoint to retrieve details of the authenticated user.
Remember that access tokens have a limited lifespan. When an access token expires, you will receive an authentication error (e.g., HTTP 401 Unauthorized). At this point, you should use your refresh_token to obtain a new access_token without requiring the user to re-authorize. The Mercadolibre API Reference provides details on specific endpoints and required scopes.
Security best practices
Adhering to security best practices is crucial when integrating with Mercadolibre's APIs to protect both your application and user data. Here are key recommendations:
-
Secure Client Secret Storage: Your
client_secretis a sensitive credential. It should never be hardcoded into your application's source code, especially in client-side applications (like browser-based JavaScript). Store it securely on your server, ideally in environment variables or a secure configuration management system. Only your backend server should have access to the client secret when exchanging authorization codes for tokens. -
HTTPS Everywhere: Always use HTTPS for all communication with Mercadolibre's APIs and for your application's redirect URIs. This encrypts data in transit, protecting sensitive information like authorization codes, access tokens, and user data from interception. HTTPS is a fundamental security requirement for OAuth 2.0.
-
Validate Redirect URIs: Ensure that the redirect URIs registered with Mercadolibre are precise and under your control. Always validate the
redirect_uriparameter in the authorization request to prevent open redirect vulnerabilities, where an attacker could redirect users to a malicious site after authorization. -
Protect Access Tokens and Refresh Tokens:
- Access Tokens: Treat access tokens as bearer tokens. They grant access to resources to anyone who possesses them. Transmit them only over HTTPS.
- Refresh Tokens: Refresh tokens have a longer lifespan and are used to obtain new access tokens. They are even more sensitive than access tokens. Store refresh tokens securely in a backend database, encrypted at rest. Never expose refresh tokens to the client side.
-
Implement Token Expiration and Renewal: Mercadolibre's access tokens have a limited validity period. Your application must be designed to handle token expiration gracefully. Use the refresh token to obtain a new access token when the current one expires, reducing the need for users to re-authorize frequently. The Mercadolibre OAuth 2.0 guide details token expiration and refresh mechanisms.
-
Least Privilege Principle: Request only the minimum necessary scopes (permissions) from the user. For instance, if your application only needs to read user profiles, do not request permissions to manage listings or process payments. This limits the potential impact if your application is compromised.
-
Error Handling: Implement robust error handling for authentication failures. Distinguish between temporary network issues and permanent authorization errors. Provide clear, user-friendly messages without exposing sensitive internal details.
-
Regular Security Audits: Periodically review your application's code and infrastructure for potential security vulnerabilities related to authentication and authorization. Stay updated with Mercadolibre's security advisories and best practices.