Authentication overview
Blockfrost Cardano requires authentication for all API requests to ensure secure and controlled access to its blockchain data and services. This authentication mechanism verifies the identity of the requesting application or user, linking API calls to a specific project and managing usage limits. The primary method for authenticating with Blockfrost is through the use of API keys, which are unique identifiers assigned to each developer project. These keys must be included in the HTTP headers of every request sent to the Blockfrost API endpoints. The system is designed to provide a straightforward integration experience while maintaining security standards for accessing Cardano, IPFS, and Arweave blockchain data.
Authentication is essential for several reasons, including:
- Access Control: Restricting API access to authorized users and applications.
- Usage Tracking: Monitoring request volumes against project-specific limits, including the Blockfrost free tier.
- Security: Preventing unauthorized data access and misuse of resources.
- Billing: Associating API usage with specific accounts for paid plans.
Understanding the authentication process is a prerequisite for any developer integrating with Blockfrost's services, as unauthenticated requests will result in an error response.
Supported authentication methods
Blockfrost primarily supports API key authentication. This method involves generating a unique key for each project within the Blockfrost dashboard and then including this key in the project_id header for every API request. This approach is common for many web APIs due to its simplicity and effectiveness in identifying clients.
API Key Authentication
API keys act as a secret token that authenticates your application when it makes requests to the Blockfrost API. Each key is tied to a specific project, allowing developers to manage different applications or environments (e.g., development, staging, production) with separate keys. This isolation enhances security and simplifies key rotation or revocation if a key is compromised for one project without affecting others.
How it works:
- A developer creates an account and then a project on the Blockfrost dashboard.
- A unique API key is generated and assigned to the new project.
- When making an API request, the developer includes this API key in the
project_idHTTP header. - The Blockfrost API receives the request, validates the API key, and grants access if the key is valid and active.
While API keys offer a straightforward authentication mechanism, they should be treated with the same level of confidentiality as passwords. Best practices for handling API keys include avoiding hardcoding them directly into source code and utilizing environment variables or secure configuration management systems.
Authentication Method Summary
| Method | When to Use | Security Level |
|---|---|---|
| API Key | All API interactions with Blockfrost. Suitable for server-side applications, scripts, and client-side applications where the key can be securely stored or proxied. | Moderate. Relies on the secrecy of the key. Requires careful handling to prevent exposure. |
Getting your credentials
To obtain your Blockfrost API key, you must first create an account and then a project on the Blockfrost platform. The process is designed to be user-friendly, guiding you through the necessary steps to generate and manage your credentials.
Steps to obtain an API key:
- Create a Blockfrost Account: Navigate to the Blockfrost homepage and sign up for an account. This typically involves providing an email address and creating a password.
- Log In to the Dashboard: Once your account is created and verified, log in to the Blockfrost dashboard.
- Create a New Project: Within the dashboard, you will find an option to create a new project. You will need to provide a name for your project and select the network you intend to use (e.g., Cardano Mainnet, Cardano Testnet, IPFS, Arweave). Each project corresponds to a specific API key.
- Retrieve Your API Key: After creating the project, Blockfrost will generate a unique API key for it. This key will be displayed prominently on your project's details page within the dashboard. Copy this key immediately and store it securely, as it may not be fully visible again for security reasons. The Blockfrost API reference documentation provides further details on managing project keys.
Each project can have a single active API key. If you need to rotate your key or suspect it has been compromised, you can generate a new key through the dashboard, which will invalidate the old one. This process ensures that you maintain control over who can access your Blockfrost resources.
Authenticated request example
Once you have obtained your API key, you can use it to make authenticated requests to the Blockfrost API. The key must be included in the project_id HTTP header for every request. Below are examples demonstrating how to make an authenticated request using common programming languages and tools.
Example using cURL
This cURL example retrieves the latest block on the Cardano mainnet:
curl -H "project_id: YOUR_BLOCKFROST_API_KEY" \
https://cardano-mainnet.blockfrost.io/api/v0/blocks/latest
Replace YOUR_BLOCKFROST_API_KEY with your actual API key.
Example using Python (requests library)
This Python example performs the same request:
import requests
import os
api_key = os.environ.get("BLOCKFROST_API_KEY") # Recommended: use environment variables
headers = {
"project_id": api_key
}
url = "https://cardano-mainnet.blockfrost.io/api/v0/blocks/latest"
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
print(response.json())
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except Exception as err:
print(f"An error occurred: {err}")
This example demonstrates retrieving the API key from an environment variable, which is a recommended security practice.
Example using JavaScript (fetch API)
For client-side or Node.js applications, you can use the fetch API:
const apiKey = process.env.BLOCKFROST_API_KEY; // For Node.js, use environment variables
// For client-side, ensure key is securely handled (e.g., proxied through a backend)
async function getLatestBlock() {
try {
const response = await fetch('https://cardano-mainnet.blockfrost.io/api/v0/blocks/latest', {
headers: {
'project_id': apiKey
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching latest block:', error);
}
}
getLatestBlock();
When using client-side JavaScript, direct exposure of API keys can be a security risk. Consider proxying requests through a backend server to keep your API key confidential, as advised by general API key best practices from Google Developers.
Security best practices
Properly securing your API keys is crucial to prevent unauthorized access to your Blockfrost account and potential misuse of your allocated request limits. Adhering to these best practices will help maintain the integrity and security of your applications.
1. Treat API Keys as Sensitive Information
Consider your Blockfrost API key as sensitive as a password. It grants access to your project's resources and usage data. Never commit API keys directly into your source code repositories, especially public ones like GitHub.
2. Use Environment Variables
Store API keys in environment variables rather than hardcoding them into your application's source code. This practice keeps keys out of your codebase and allows for easy configuration changes across different deployment environments (development, staging, production) without modifying code. Most programming languages and frameworks provide straightforward ways to access environment variables.
3. Implement Server-Side Proxies for Client-Side Applications
If your application is client-side (e.g., a web application running in a browser), avoid directly embedding your Blockfrost API key in the client-side code. Adversaries can easily inspect client-side code and extract keys. Instead, route all API requests through a secure backend server that adds the API key before forwarding the request to Blockfrost. This server acts as a proxy, keeping your API key confidential on the server side.
4. Restrict API Key Usage (if applicable)
While Blockfrost API keys are currently project-wide, always check for any future updates that might allow for IP address restrictions or other usage constraints. If such features become available, implement them to limit where and how your key can be used, adding another layer of security.
5. Regularly Rotate API Keys
Periodically rotate your API keys, even if you don't suspect a compromise. This practice reduces the window of opportunity for a compromised key to be exploited. Blockfrost allows you to generate new keys from your dashboard, which will invalidate the old one. Establish a regular schedule for key rotation as part of your security policy.
6. Monitor API Usage
Regularly monitor your Blockfrost project's API usage from your dashboard. Unusual spikes in request volume could indicate a compromised key or an application error. Early detection can help mitigate potential issues.
7. Secure Your Development Environment
Ensure that your development machines and deployment environments are secure. Use strong passwords, enable multi-factor authentication where available, and keep software updated to protect against vulnerabilities that could expose your API keys.
8. Understand Rate Limits and Error Handling
Be aware of Blockfrost's rate limits and implement robust error handling in your application. Excessive requests or improper error handling could potentially expose information or lead to service interruptions. While not directly an authentication security measure, it contributes to overall application resilience and prevents unintended exposure through debugging or logging.