Authentication overview
CARTO provides a cloud-native geospatial platform designed for spatial data analysis, visualization, and application development. Securely accessing CARTO's APIs and services requires proper authentication to ensure that only authorized users and applications can interact with spatial datasets, analyses, and platform functionalities. CARTO supports industry-standard authentication mechanisms, primarily API Keys and OAuth 2.0, to accommodate a range of integration scenarios from server-side scripts to interactive web applications.
The choice of authentication method depends on the application's architecture, its interaction with user data, and the required level of security and authorization granularity. API Keys offer a straightforward approach for direct application access, while OAuth 2.0 provides a more robust framework for delegated authorization, allowing users to grant third-party applications limited access to their CARTO resources without sharing their credentials directly. Understanding the strengths and appropriate use cases for each method is essential for building secure and scalable geospatial solutions on the CARTO platform.
For detailed information on specific API endpoints and their authentication requirements, developers can consult the CARTO Engine API reference documentation.
Supported authentication methods
CARTO offers two primary authentication methods:
- API Keys: This is a simple, token-based authentication method suitable for server-side applications, scripts, and direct API access where user context is not required. An API key grants access to the resources and permissions associated with the CARTO account that generated it.
- OAuth 2.0: This open standard for authorization is designed for applications that need to access a user's CARTO resources on their behalf, without requiring the user to share their credentials. OAuth 2.0 is ideal for client-side applications, mobile apps, and integrations where user consent and delegated access are critical. The OAuth 2.0 authorization framework defines various grant types to suit different application types.
Comparison of Authentication Methods
| Method | When to Use | Security Level |
|---|---|---|
| API Keys | Server-side applications, backend services, scripts, development, internal tools where direct account access is acceptable. | Moderate (requires careful handling and secure storage to prevent unauthorized access). |
| OAuth 2.0 | Client-side applications (web/mobile), third-party integrations, applications requiring user consent and delegated access to specific resources. | High (tokens are short-lived, scopes limit access, user consent is explicit, and credentials are not shared directly with the client). |
Getting your credentials
To authenticate with CARTO, you will need to obtain the appropriate credentials from your CARTO account dashboard.
For API Keys:
- Log in to your CARTO account.
- Navigate to the settings or API keys section within your dashboard.
- Generate a new API key. It is recommended to create separate API keys for different applications or environments to facilitate key rotation and access management.
- Store your API key securely. Treat it like a password.
Refer to the CARTO documentation on API Keys for specific steps on key generation and management.
For OAuth 2.0:
To use OAuth 2.0, you must register your application with CARTO to obtain a Client ID and Client Secret.
- Log in to your CARTO account.
- Access the Developer or Applications section in your dashboard.
- Register a new application, providing details such as the application name, redirect URIs (callback URLs), and relevant scopes your application will require.
- Upon registration, CARTO will provide you with a Client ID and a Client Secret. The Client Secret should be kept confidential and never exposed in client-side code.
- Your application will then initiate the OAuth 2.0 flow, typically starting with an authorization request to CARTO, redirecting the user for consent, and finally exchanging an authorization code for an Access Token and optionally a Refresh Token. The Access Token is used to make API calls on behalf of the user, while the Refresh Token allows your application to obtain new Access Tokens without requiring the user to re-authenticate.
For a detailed guide on implementing OAuth 2.0 with CARTO, consult the CARTO OAuth 2.0 documentation.
Authenticated request example
Here are examples of how to make authenticated requests using both API Keys and OAuth 2.0.
Using an API Key (Python example):
This example demonstrates fetching data from a CARTO dataset using an API key in a Python script. Replace YOUR_CARTO_ACCOUNT_NAME, YOUR_API_KEY, and your_dataset_name with your specific details.
import requests
CARTO_ACCOUNT_NAME = "YOUR_CARTO_ACCOUNT_NAME"
CARTO_API_KEY = "YOUR_API_KEY"
DATASET_NAME = "your_dataset_name"
# Construct the SQL API endpoint for your dataset
sql_api_url = f"https://{CARTO_ACCOUNT_NAME}.carto.com/api/v2/sql"
# Define your SQL query to fetch data
query = f"SELECT * FROM {DATASET_NAME} LIMIT 10"
# Parameters for the API request
params = {
"q": query,
"api_key": CARTO_API_KEY
}
try:
response = requests.get(sql_api_url, params=params)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
data = response.json()
print("Successfully fetched data:")
print(data)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if response.status_code:
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
Using OAuth 2.0 Access Token (JavaScript example for browser):
This conceptual example shows how a client-side JavaScript application might use an OAuth 2.0 Access Token to make an authenticated request. This assumes you have already completed the OAuth flow and obtained an accessToken.
const accessToken = "YOUR_OAUTH_ACCESS_TOKEN"; // Obtained after successful OAuth flow
const cartoAccountName = "YOUR_CARTO_ACCOUNT_NAME";
const datasetName = "your_dataset_name";
const sqlApiUrl = `https://${cartoAccountName}.carto.com/api/v2/sql`;
const query = `SELECT * FROM ${datasetName} LIMIT 5`;
fetch(`${sqlApiUrl}?q=${encodeURIComponent(query)}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log("Successfully fetched data with OAuth:", data);
})
.catch(error => {
console.error("Error fetching data with OAuth:", error);
});
Security best practices
Adhering to security best practices is crucial when implementing authentication for CARTO APIs to protect your data and applications.
- API Key Management:
- Environment Variables: Never hardcode API keys directly into your source code. Use environment variables (e.g., in server-side applications) or secure configuration management systems.
- Access Control: Grant API keys only the minimum necessary permissions (least privilege principle).
- Rotation: Regularly rotate your API keys, especially if there's any suspicion of compromise or after personnel changes.
- Logging & Monitoring: Implement logging for API key usage and monitor for unusual activity that might indicate a breach.
- HTTPS: Always use HTTPS for all API communications to encrypt data in transit and protect API keys from interception.
- OAuth 2.0 Best Practices:
- Secure Client Secret: The Client Secret must be kept confidential and stored securely on your server. It should never be exposed in client-side code (e.g., JavaScript in a browser).
- Redirect URIs: Register specific and secure redirect URIs (callback URLs) with CARTO. Avoid using wildcard URLs, which can be exploited for authorization code interception attacks, as described by the IETF.
- Scopes: Request only the necessary OAuth scopes for your application's functionality. This limits the damage if an access token is compromised.
- Token Storage: Store access tokens securely. For web applications, consider HTTP-only, secure cookies or in-memory storage for short-lived tokens. For refresh tokens, ensure they are encrypted and stored in a highly secure manner, as they can be used to obtain new access tokens.
- State Parameter: Implement the
stateparameter in your OAuth 2.0 authorization requests to prevent Cross-Site Request Forgery (CSRF) attacks. - PKCE: For public clients (like mobile or single-page applications) that cannot securely store a Client Secret, implement the Proof Key for Code Exchange (PKCE) extension to OAuth 2.0. This prevents authorization code interception attacks.
- General Security Practices:
- Input Validation: Always validate and sanitize any user-supplied input to prevent injection attacks (e.g., SQL injection when constructing queries).
- Error Handling: Implement robust error handling that does not expose sensitive information in error messages.
- Least Privilege: Ensure that the CARTO account or assigned roles used for authentication have only the minimum necessary permissions to perform their required tasks.
- Regular Audits: Periodically audit your application's authentication and authorization mechanisms.