Authentication overview
Authentication for The Graph differs based on whether you are interacting with the Hosted Service or the Decentralized Network. The Hosted Service, which provides a managed infrastructure for running subgraphs, primarily uses API keys to control access to private subgraphs, manage query volume, and track usage for billing. These API keys are generated through the Graph Dashboard and are associated with a user account. They serve as a mechanism to identify the requester and apply usage policies, including query limits and billing rules for paid tiers beyond the free query allowance.
In contrast, the Decentralized Network operates on a different authentication model. Queries submitted to the Decentralized Network are paid for directly by consumers using GRT (Graph Tokens). Authenticating these queries involves cryptographically signing the query with a user's wallet, which holds the GRT. This signature verifies the identity of the query sender and authorizes the payment from their linked wallet, removing the need for traditional API keys in the query process itself. Indexers, who process queries on the Decentralized Network, verify these signatures before serving data, ensuring the integrity and payment for the service. The choice of authentication method is directly tied to the operational model and billing structure of each service offering.
Supported authentication methods
The Graph supports distinct authentication methods tailored to its Hosted Service and Decentralized Network environments. The Hosted Service relies on API keys for access control and usage tracking, while the Decentralized Network uses cryptographic signatures for decentralized query payments.
| Method | When to Use | Security Level |
|---|---|---|
| API Keys | Accessing private subgraphs on the Hosted Service, deploying subgraphs to the Hosted Service, exceeding free query limits on public hosted subgraphs. | Moderate: Grants access to specific account resources. Requires secure storage and transmission via HTTPS. |
| Cryptographic Signatures (via Wallet) | Querying subgraphs directly on The Graph's Decentralized Network, participating in the network as an Indexer, Curator, or Delegator. | High: Relies on blockchain-level cryptographic security. Private keys remain with the user; only signed messages are transmitted. |
| Public Access (No Auth) | Querying public subgraphs on the Hosted Service within the free tier (first 100,000 queries per month). | Low (N/A): No authentication required as access is public and unmetered up to the free tier limit. |
For operations on the Hosted Service, API keys are crucial for managing access to subgraphs that are not publicly available or for tracking usage beyond the initial free tier. These keys provide a simple and effective way to secure HTTP-based GraphQL requests. The Decentralized Network's approach leverages the inherent security of blockchain transactions, where every query is effectively a micro-transaction authorized by the user's wallet, ensuring a trustless environment for data access and payment. This model aligns with the broader principles of decentralized applications and Web3 infrastructure, as detailed in resources like MDN Web Docs on Web3.
Getting your credentials
To obtain credentials for The Graph, the process varies depending on whether you are using the Hosted Service or engaging with the Decentralized Network.
For the Hosted Service (API Keys):
- Create an Account: Navigate to The Graph Hosted Service and sign up for an account. This typically involves connecting a Web3 wallet (e.g., MetaMask) or using traditional email-based registration.
- Access the Dashboard: Once logged in, go to your Graph Dashboard.
- Generate an API Key: Within the dashboard, locate the 'API Keys' section. You will have the option to generate a new API key. When generating, you may be prompted to provide a name for the key to help with organization and potentially specify permissions, though for querying, the default permissions are often sufficient.
- Store Securely: Copy the generated API key immediately. The key is typically shown only once at creation.
- Link to Subgraphs: For private subgraphs, ensure your API key is linked or configured for the specific subgraph you intend to query or deploy.
For the Decentralized Network (Wallet-based Authentication):
- Set Up a Web3 Wallet: You will need a compatible Web3 wallet (e.g., MetaMask, WalletConnect) that can hold GRT tokens and sign transactions. Ensure it's connected to a network compatible with The Graph Network (e.g., Ethereum mainnet or a supported layer-2).
- Acquire GRT Tokens: Purchase or acquire GRT tokens, as these are used to pay for queries on the Decentralized Network.
- Connect Wallet to dApp/Client: When querying a subgraph on the Decentralized Network, your client application (e.g., a dApp front-end) will prompt you to connect your Web3 wallet.
- Authorize Queries: Each query typically involves a micro-payment in GRT, which requires a cryptographic signature from your connected wallet to authorize the transaction. The wallet interface will guide you through signing these requests.
For more detailed instructions on managing your API keys or interacting with the network, refer to The Graph's querying documentation.
Authenticated request example
This example demonstrates how to make an authenticated request to The Graph's Hosted Service using an API key with a GraphQL client. The API key is typically included in the Authorization header or sometimes as a custom header, as specified by The Graph's endpoint configuration.
Example: GraphQL Query with API Key (Hosted Service)
Assuming you have a GraphQL endpoint for a private subgraph on the Hosted Service and an API key:
query MySubgraphQuery {
users(first: 10) {
id
address
balance
}
}
Using curl to execute this query with an API key:
API_KEY="YOUR_GRAPH_API_KEY"
SUBGRAPH_URL="https://api.thegraph.com/subgraphs/id/YOUR_SUBGRAPH_ID"
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_KEY" \
--data '{ "query": "query MySubgraphQuery { users(first: 10) { id address balance } }" }' \
$SUBGRAPH_URL
In a JavaScript/TypeScript environment using a library like graphql-request:
import { GraphQLClient, gql } from 'graphql-request';
const API_KEY = 'YOUR_GRAPH_API_KEY';
const SUBGRAPH_URL = 'https://api.thegraph.com/subgraphs/id/YOUR_SUBGRAPH_ID';
const client = new GraphQLClient(SUBGRAPH_URL, {
headers: {
authorization: `Bearer ${API_KEY}`,
},
});
const query = gql`
query MySubgraphQuery {
users(first: 10) {
id
address
balance
}
}
`;
async function fetchData() {
try {
const data = await client.request(query);
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
For Decentralized Network queries, the interaction would typically be handled by a Web3-enabled client or dApp, prompting the user for wallet signatures, rather than using a direct HTTP header for authentication.
Security best practices
Maintaining the security of your authentication credentials for The Graph is critical to prevent unauthorized access to your subgraphs and control your query costs. Adhering to these best practices helps safeguard your operations on both the Hosted Service and the Decentralized Network.
API Key Management (Hosted Service):
- Treat API Keys as Sensitive: API keys grant access to your account's resources and can incur costs. Treat them with the same level of security as private keys or passwords.
- Avoid Hardcoding: Never embed API keys directly into your source code. Use environment variables, configuration files, or secure key management systems to store and retrieve them.
- Restrict Permissions: If The Graph's dashboard allows, generate API keys with the minimum necessary permissions for their intended use. For example, a key used only for querying should not have deployment permissions.
- Rotate Keys Regularly: Periodically generate new API keys and revoke old ones. This minimizes the window of exposure if a key is compromised.
- Use HTTPS: Always ensure that all API requests are made over HTTPS to encrypt the communication and prevent eavesdropping on your API keys during transit.
- IP Whitelisting (if available): If The Graph offers IP whitelisting, configure your API keys to only accept requests from known and trusted IP addresses. This adds an extra layer of security against unauthorized usage.
- Monitor Usage: Regularly review your subgraph query usage in the Graph Dashboard to detect any unusual activity that might indicate a compromised key.
Wallet and Private Key Management (Decentralized Network):
- Secure Private Keys: Your wallet's private key controls your GRT tokens and authorizes queries. Store private keys in secure hardware wallets (e.g., Ledger, Trezor) or robust key management solutions. Never share your private key or seed phrase.
- Use Reputable Wallets: Only use well-established and audited Web3 wallets for interacting with the Decentralized Network.
- Review Transactions Carefully: Before signing any transaction or query authorization with your wallet, carefully review the details presented by your wallet interface to ensure it matches your intended action.
- Phishing Awareness: Be wary of phishing attempts that try to trick you into revealing your wallet's seed phrase or private key. Always verify the URL and source of any request for wallet connection or signature.
- Keep Software Updated: Ensure your operating system, browser, and wallet software are always updated to the latest versions to benefit from security patches.
General Security Practices:
- Principle of Least Privilege: Grant users and applications only the permissions they need to perform their specific tasks.
- Audit Logs: Where available, review audit logs for unusual access patterns or failed authentication attempts.
- Educate Your Team: Ensure all developers and operators understand the importance of secure credential management and follow established security protocols.