Authentication overview
OKEx provides programmatic access to its exchange services, including spot trading, derivatives, market data, and account management, through a REST API and WebSocket API. Authentication for these interfaces is critical for securing user accounts and transactions. The primary method for authenticating API requests on OKEx involves a combination of API keys, secret keys, and a passphrase, utilizing a Hash-based Message Authentication Code (HMAC) signature mechanism.
This approach requires clients to sign each request with their unique secret key, which the OKEx server then verifies. The HMAC-SHA256 algorithm is employed for generating these signatures, offering a robust method for ensuring both the authenticity and integrity of API requests. This prevents unauthorized parties from impersonating a user or tampering with request data during transmission.
Users can manage their API keys within the OKEx platform, where they can generate new keys, set specific permissions (e.g., read-only, trade, withdraw), and configure security enhancements like IP whitelisting. The system is designed to allow granular control over API access, enabling developers to tailor permissions to the specific needs of their applications while minimizing potential risks.
Supported authentication methods
OKEx primarily supports HMAC-based authentication for its API endpoints. This method is standard for securing interactions with cryptocurrency exchanges, providing a cryptographic proof of identity for each request without transmitting the secret key directly. The process involves generating a unique signature for each API call, which is then included in the request headers.
The details of the HMAC signature process are outlined in the OKEx API documentation, specifying the components that must be included in the signature string: timestamp, HTTP method, request path, and request body (if applicable). This comprehensive approach ensures that every part of a request is authenticated.
While HMAC-SHA256 is the core authentication mechanism, OKEx also incorporates other security features that complement the authentication process. These include:
- API Key Management: Users create and manage API keys with configurable permissions (read-only, trade, withdraw) and expiration dates.
- IP Whitelisting: Restricting API access to a predefined list of IP addresses, significantly reducing the risk of unauthorized access.
- Passphrase: An additional security layer, acting as a secondary password for API keys, which must be included in the signature generation.
The table below summarizes the primary authentication method and its characteristics:
| Method | When to Use | Security Level |
|---|---|---|
| HMAC-SHA256 (API Key, Secret Key, Passphrase) | All REST API and WebSocket API interactions requiring authenticated access (e.g., trading, account balance queries, order management). | High: Cryptographically signs each request, preventing tampering and ensuring sender authenticity. Enhanced by IP whitelisting and 2FA. HMAC is a widely accepted method for message authentication, as detailed by the IETF in RFC 2104. |
Getting your credentials
To interact with the OKEx API, you must first generate API credentials from your OKEx account. This process typically involves several steps to ensure security and proper permissioning:
- Log In to Your OKEx Account: Access your account through the official OKEx website.
- Navigate to API Settings: In your user profile or security settings, locate the 'API' or 'API Key Management' section.
- Create a New API Key: Select the option to create a new API key. You will typically be prompted to provide a name for the key to help you identify its purpose (e.g., 'Trading Bot Key', 'Market Data Viewer').
- Set Permissions: Configure the permissions for your new API key. OKEx allows you to choose from various access levels, such as 'Read-only', 'Trade', and 'Withdraw'. It is a best practice to grant only the minimum necessary permissions for your application to function. For example, a market data application may only require 'Read-only' access, while a trading bot would need 'Trade' permissions.
- Set IP Whitelist (Optional but Recommended): If your application will be making requests from a static IP address, you can specify a list of allowed IP addresses. This enhances security by ensuring that only requests originating from these IPs are accepted, even if your API key is compromised.
- Create a Passphrase: You will be required to create a passphrase for your API key. This acts as an additional layer of security and must be included in the signature generation process. Remember this passphrase securely, as it cannot be retrieved if lost.
- Confirm Creation: After setting the permissions and passphrase, confirm the creation. OKEx will then display your API Key and Secret Key. The Secret Key is shown only once upon creation; make sure to copy and store it immediately and securely. If you lose your Secret Key, you will need to delete the existing API key and create a new one.
- Store Credentials Securely: Store your API Key, Secret Key, and Passphrase in a secure location. Avoid hardcoding them directly into your application's source code. Environment variables or a secure configuration management system are preferred methods for credential storage.
For detailed, step-by-step instructions with screenshots, refer to the official OKX API documentation on authentication.
Authenticated request example
Authenticating an OKEx API request involves constructing a signature string and signing it with your Secret Key using HMAC-SHA256. The resulting signature is then included in the OK-ACCESS-SIGN header of your HTTP request. Below is a conceptual example for a GET request in Python, demonstrating the key components of signature generation.
Signature String Components:
timestamp: Current UTC time in ISO 8601 format (e.g.,2023-01-01T12:00:00.000Z) or Unix timestamp in seconds or milliseconds, depending on the API version.method: HTTP method (e.g.,GET,POST).requestPath: The API endpoint path (e.g.,/api/v5/account/balance).body: The request body forPOSTorPUTrequests. Empty string forGETorDELETE.passphrase: The passphrase you set for your API key.
Python Example (Conceptual):
This example illustrates how to generate an HMAC signature for a GET request using Python. It assumes you have your API_KEY, SECRET_KEY, and PASSPHRASE readily available.
import hmac
import hashlib
import base64
import json
import time
import requests
# Your OKEx API Credentials
API_KEY = "YOUR_API_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"
PASSPHRASE = "YOUR_PASSPHRASE"
# API Request Details
METHOD = "GET"
REQUEST_PATH = "/api/v5/account/balance"
HOST = "www.okx.com"
BODY = "" # Empty for GET requests
def generate_signature(timestamp, method, request_path, body):
message = str(timestamp) + method + request_path + body
# The secret key needs to be decoded from base64 if it's base64 encoded
# For OKX, the secret key is usually provided as a raw string.
# If it was base64 encoded, you'd use base64.b64decode(SECRET_KEY)
hmac_key = SECRET_KEY.encode('utf-8')
signature = hmac.new(hmac_key, message.encode('utf-8'), hashlib.sha256).digest()
return base64.b64encode(signature).decode('utf-8')
def send_authenticated_request():
# Get current timestamp in ISO 8601 format for OKX v5 API
# Example: 2023-01-01T12:00:00.000Z
timestamp = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
signature = generate_signature(timestamp, METHOD, REQUEST_PATH, BODY)
headers = {
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": PASSPHRASE,
"Content-Type": "application/json"
}
url = f"https://{HOST}{REQUEST_PATH}"
try:
response = requests.request(METHOD, url, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
print("Response Status:", response.status_code)
print("Response Body:", json.dumps(response.json(), indent=2))
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
print(f"Response content: {response.text}")
except Exception as err:
print(f"Other error occurred: {err}")
# Call the function to send the request
# send_authenticated_request()
This example demonstrates the core logic. In a real-world application, you would integrate this into your request handling logic, ensuring proper error handling and secure credential management. For specific API endpoint details and the most up-to-date timestamp format, always consult the OKEx API reference documentation.
Security best practices
When integrating with the OKEx API, implementing robust security measures is crucial to protect your assets and data. Adhering to these best practices can mitigate common risks associated with API usage:
- Principle of Least Privilege: Grant API keys only the minimum necessary permissions. For example, if your application only needs to read market data, do not grant it trading or withdrawal permissions. This limits the damage if a key is compromised.
- IP Whitelisting: Always configure IP whitelisting for your API keys. This restricts API access to a predefined list of trusted IP addresses, preventing unauthorized requests from unknown locations. If your application's IP address changes frequently, consider using a static IP proxy or a secure cloud environment with predictable egress IPs.
- Secure Storage of Credentials: Never hardcode API keys, secret keys, or passphrases directly into your application's source 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 these credentials.
- Rotate API Keys Regularly: Periodically rotate your API keys. This practice reduces the window of opportunity for an attacker if a key is ever compromised. The frequency of rotation depends on your security policy and risk assessment.
- Implement Strong Passphrases: Use a complex and unique passphrase for each API key. Avoid using easily guessable phrases or reusing passphrases from other services.
- Monitor API Usage: Regularly monitor your API logs for any unusual activity, such as a sudden increase in requests, requests from unfamiliar IP addresses, or failed authentication attempts. Set up alerts for suspicious patterns.
- Use Secure Communication (HTTPS): Ensure all API requests are made over HTTPS to encrypt data in transit, protecting against eavesdropping and man-in-the-middle attacks. OKEx API endpoints are typically only accessible via HTTPS.
- Error Handling and Logging: Implement comprehensive error handling and logging for API interactions. This helps in quickly identifying and responding to authentication failures or other security incidents. However, be cautious not to log sensitive information like API keys or secret keys.
- Time Synchronization: Ensure that the system clock of your client application is accurately synchronized with Network Time Protocol (NTP) servers. Timestamp discrepancies can lead to authentication failures, as the server verifies the timestamp as part of the signature.
- Two-Factor Authentication (2FA): While API keys handle programmatic access, ensure your main OKEx account is protected with 2FA (e.g., Google Authenticator, SMS 2FA) to secure credential management and other critical actions. This is a fundamental layer of account security, as highlighted by Google's 2FA guidance.
By diligently applying these security best practices, developers can significantly enhance the security posture of their OKEx API integrations, protecting both their own and their users' assets.