Authentication overview
Coinbase provides authentication mechanisms designed to secure programmatic access to user accounts and market data. The choice of authentication method depends on the application's nature and the level of access required. API keys are typically used for server-to-server interactions, enabling applications to manage wallets, initiate trades, or access account information directly. OAuth 2.0, conversely, facilitates delegated authorization, allowing third-party applications to access a user's Coinbase account without the application ever handling the user's direct credentials. This approach is common for user-facing applications that integrate with Coinbase services.
Both methods incorporate security measures to protect sensitive data and transactions. API key authentication relies on cryptographic signing of requests, while OAuth 2.0 leverages token-based access with refresh tokens for continued access without re-authentication. Understanding the appropriate use case for each method is fundamental to building secure and compliant applications on the Coinbase platform. Detailed guidance for each method is available in the Coinbase Cloud documentation.
Supported authentication methods
Coinbase supports two primary authentication methods for its APIs:
- API Keys: Used for direct programmatic access, typically by backend services or scripts.
- OAuth 2.0: Used for delegated access, allowing third-party applications to act on behalf of a Coinbase user.
API Key Authentication
API key authentication for Coinbase APIs involves generating a unique key pair (API key and secret) from the Coinbase developer console. Each request made to a protected API endpoint must be signed using the API secret. This signing process typically uses HMAC-SHA256, combining the request method, request path, body, and a timestamp. The resulting signature is then included in the request headers.
This method ensures that only requests originating from an entity possessing the secret can be processed. Permissions for API keys are granular, allowing developers to restrict access to specific functionalities like viewing account balances, trading, or managing addresses. It is critical to manage API secrets securely and rotate them regularly as a best practice.
OAuth 2.0 Authentication
OAuth 2.0 is an authorization framework that enables an application to obtain limited access to a user's protected resources on an HTTP service, such as Coinbase, without exposing the user's credentials to the application. Coinbase implements the OAuth 2.0 Authorization Code Grant flow, which is suitable for web applications.
The flow generally involves:
- The application redirects the user to Coinbase for authorization.
- The user logs in to Coinbase and grants the application specific permissions (scopes).
- Coinbase redirects the user back to the application with an authorization code.
- The application exchanges this authorization code for an access token and a refresh token using its client ID and client secret.
- The access token is then used to make API calls on behalf of the user.
Scopes define the exact permissions an application requests, such as wallet:accounts:read or wallet:buys:create. Developers should request only the minimum necessary scopes to adhere to the principle of least privilege. The use of Proof Key for Code Exchange (PKCE) is recommended for public clients to mitigate authorization code interception attacks, as detailed in the Coinbase OAuth 2.0 authentication guide.
Authentication Method Comparison
The following table summarizes the key characteristics and use cases for Coinbase's supported authentication methods:
| Method | When to Use | Security Level | Credential Type |
|---|---|---|---|
| API Key (HMAC-SHA256) | Server-side applications, backend services, personal scripts, direct account management | High (requires secure secret management) | API Key, API Secret |
| OAuth 2.0 (Authorization Code Grant with PKCE) | User-facing web/mobile applications, third-party integrations requiring delegated access | High (prevents sharing user credentials with app) | Client ID, Client Secret (for confidential clients), Access Token, Refresh Token |
Getting your credentials
To obtain authentication credentials for Coinbase APIs, developers must navigate to the Coinbase Developer Dashboard.
For API Keys:
- Log in to your Coinbase account.
- Access the API settings or developer section.
- Generate a new API key. During this process, you will be prompted to define the permissions (scopes) for the API key. Select only the permissions essential for your application's functionality.
- The API secret will be displayed once, upon creation. It is crucial to store this secret securely immediately, as it cannot be retrieved again.
- Whitelist IP addresses if your application operates from a fixed set of IP addresses for an additional layer of security. This restricts API calls to only those specified IPs.
Refer to the Coinbase API key authentication documentation for detailed, step-by-step instructions on key generation and management.
For OAuth 2.0:
- Register your application on the Coinbase Developer Dashboard. This process will require providing details such as your application's name, description, and authorized redirect URIs.
- Upon registration, Coinbase will issue a Client ID and Client Secret for your application. The Client Secret should be treated with the same level of confidentiality as an API secret.
- Configure your application's redirect URIs. These are the URLs where Coinbase will redirect the user after they authorize your application. Ensure these URIs are secure (HTTPS) and strictly controlled.
- When initiating the OAuth flow, specify the required scopes. These scopes determine the permissions your application will request from the user.
The Coinbase OAuth 2.0 reference provides comprehensive guidance on application registration, scope definitions, and implementing the authorization flow.
Authenticated request example
Here's an example of an authenticated request using API keys in Python, demonstrating how to sign a request to retrieve user accounts. This example utilizes the requests library and standard Python libraries for cryptographic operations.
import time
import hmac
import hashlib
import requests
import json
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
BASE_URL = "https://api.coinbase.com/v2"
def sign_request(method, request_path, body=""):
timestamp = str(int(time.time()))
message = timestamp + method + request_path + body
signature = hmac.new(API_SECRET.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
return timestamp, signature
def get_accounts():
method = "GET"
request_path = "/v2/accounts"
timestamp, signature = sign_request(method, request_path)
headers = {
"CB-ACCESS-KEY": API_KEY,
"CB-ACCESS-SIGN": signature,
"CB-ACCESS-TIMESTAMP": timestamp,
"CB-VERSION": "2023-05-29" # Use current API version
}
response = requests.get(BASE_URL + request_path, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
return response.json()
if __name__ == "__main__":
try:
accounts_data = get_accounts()
print(json.dumps(accounts_data, indent=2))
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
print(f"Response body: {e.response.text}")
except Exception as e:
print(f"An error occurred: {e}")
This Python snippet demonstrates:
- Generating a unique timestamp for each request.
- Constructing the message string for HMAC signing, including the timestamp, HTTP method, request path, and an empty body for GET requests.
- Using
hmacandhashlibto create the SHA256 signature with the API secret. - Setting the necessary custom headers (
CB-ACCESS-KEY,CB-ACCESS-SIGN,CB-ACCESS-TIMESTAMP,CB-VERSION). - Handling potential HTTP errors gracefully.
For more detailed examples and language-specific SDK usage, consult the Coinbase API reference documentation.
Security best practices
Adhering to security best practices is crucial when integrating with Coinbase APIs to protect sensitive financial data and prevent unauthorized access. The following recommendations apply to both API key and OAuth 2.0 implementations:
Credential Management
- Secure Storage: Never hardcode API secrets or OAuth client secrets directly into your application code. Use environment variables, secure configuration files, or dedicated secret management services (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) to store credentials.
- Access Control: Implement strict access controls for who can view or modify API keys and secrets within your development team and infrastructure.
- Rotation: Regularly rotate API keys and OAuth client secrets. This minimizes the risk window if a credential is compromised.
- Least Privilege: Grant only the minimum necessary permissions (scopes) to your API keys and OAuth applications. Avoid using a single API key with broad permissions for multiple applications or purposes.
Network and Application Security
- HTTPS Everywhere: Always use HTTPS for all communications with Coinbase APIs. This encrypts data in transit, protecting against eavesdropping and man-in-the-middle attacks.
- IP Whitelisting: For API keys, restrict access to a predefined list of trusted IP addresses from which your application will make API calls. This significantly reduces the attack surface.
- Input Validation: Sanitize and validate all user inputs and data received from API calls to prevent common vulnerabilities like injection attacks.
- Error Handling: Implement robust error handling without exposing sensitive information in error messages. Log errors securely for debugging.
- Rate Limiting: Design your application to respect Coinbase's API rate limits. Excessive requests can lead to temporary blocks, and unusual patterns might trigger security alerts.
OAuth 2.0 Specific Practices
- PKCE Implementation: Always use Proof Key for Code Exchange (PKCE) for public clients (e.g., mobile apps, single-page applications) to prevent authorization code interception.
- Secure Redirect URIs: Register and strictly validate redirect URIs. Ensure they are secure (HTTPS) and specific, avoiding broad wildcard URLs.
- State Parameter: Use the
stateparameter in OAuth authorization requests to prevent Cross-Site Request Forgery (CSRF) attacks. Thestateparameter should be a unique, unguessable value generated by your application and verified upon redirection. - Token Expiration: Respect access token expiration times and use refresh tokens securely to obtain new access tokens without re-authenticating the user. Store refresh tokens securely, similar to API secrets.
For general API security principles, the OWASP API Security Top 10 provides a comprehensive resource for identifying and mitigating common API vulnerabilities.