Authentication overview
Localbitcoins, a peer-to-peer (P2P) platform for buying and selling Bitcoin, provides an API primarily for advanced users and developers to automate certain trading and account management functions. Authentication for the Localbitcoins API relies on a cryptographic signing process using API keys and secrets. This mechanism ensures that only authorized applications can interact with a user's account and that the integrity of the request data is maintained during transmission. The core principle involves generating a unique signature for each API request, which the Localbitcoins server then verifies using the same credentials.
The authentication process is critical for protecting user funds and personal information on the platform. By requiring a digitally signed request, Localbitcoins mitigates risks such as replay attacks, request tampering, and unauthorized access to user accounts. This approach aligns with common industry practices for securing RESTful APIs, where server-side verification of client-provided credentials and request integrity is paramount. Developers familiar with other cryptocurrency exchange APIs will find the Localbitcoins authentication scheme similar in concept to those employing HMAC-based signatures.
While Localbitcoins emphasizes direct user interaction for its core trading experience, the API offers capabilities for automating aspects like managing advertisements, checking trade statuses, and accessing wallet information. Proper implementation of the authentication protocol is essential for any application built on top of the Localbitcoins API to prevent security vulnerabilities and ensure reliable operation. Understanding the specific requirements for generating signatures and including them in API requests is the first step in successful integration.
Supported authentication methods
Localbitcoins primarily supports one method for authenticating API requests: HMAC-SHA256 signing with API keys. This method is standard for securing web APIs, particularly in financial contexts where data integrity and authenticity are crucial. It involves generating a unique signature for each request using a secret key shared between the client and the server.
HMAC-SHA256 with API Key
This method requires two primary credentials:
- API Key ID: A public identifier used to link the request to a specific user account.
- API Secret: A private key known only to the user and the Localbitcoins server, used to generate the cryptographic signature.
When making an API call, developers must construct a specific string that includes elements of the request, such as the nonce, the API key, the request path, the query string, and the request body. This string is then hashed using the SHA256 algorithm and the API secret as the key, resulting in a unique HMAC signature. This signature is then included in the request headers (specifically, the Apiauth-Signature header) along with other authentication parameters.
The use of a nonce (a number used once) in the signature generation process is a critical security feature. It prevents replay attacks, where an attacker might intercept a valid request and resubmit it to perform unauthorized actions. Each request must contain a new, incrementing nonce value, ensuring that even if a request is intercepted, it cannot be replayed successfully.
| Method | When to Use | Security Level |
|---|---|---|
| HMAC-SHA256 with API Key | All programmatic API interactions for trading, account management, and data retrieval. | High: Cryptographically signed requests prevent tampering and unauthorized access. |
Getting your credentials
To use the Localbitcoins API, you must generate an API key ID and an API secret from within your Localbitcoins account. This process typically involves navigating to your account settings or a dedicated API access section. Follow these general steps:
- Log in to your Localbitcoins account: Access the platform via its official website.
- Navigate to API access settings: Look for a section like "API Access" or "Account Security" in your profile settings. The exact path may vary but is usually found under your user menu or dashboard.
- Generate new API credentials: There will typically be an option to "Generate new API key" or similar. Upon generation, Localbitcoins will display your API Key ID and API Secret. The API Secret is often shown only once, immediately after generation, so it is crucial to record it securely at this point.
- Set permissions (if applicable): Some platforms allow you to define specific permissions for your API key (e.g., read-only, trade execution). Configure these permissions according to the needs of your application to adhere to the principle of least privilege.
- Store credentials securely: Once generated, store your API Key ID and API Secret in a secure location. Avoid hardcoding them directly into your application code, especially if the code is publicly accessible. Environment variables, secret management services, or secure configuration files are recommended.
Localbitcoins may also provide options to revoke existing API keys or regenerate them, which is a vital security feature if you suspect your credentials have been compromised or periodically as part of a security rotation policy. Always refer to the official Localbitcoins API documentation for the most current and specific instructions on credential generation and management, located at Localbitcoins API documentation.
Authenticated request example
Authenticating a request to the Localbitcoins API involves creating a specific signature and including it in the request headers. This example illustrates how to make a signed GET request to retrieve user information using Python. The core components are the API Key ID, API Secret, a nonce, and the request details.
import hmac
import hashlib
import time
import requests
# --- Your Localbitcoins Credentials ---
API_KEY_ID = "YOUR_API_KEY_ID" # Replace with your actual API Key ID
API_SECRET = "YOUR_API_SECRET" # Replace with your actual API Secret
# --- Request Parameters ---
BASE_URL = "https://localbitcoins.com"
PATH = "/api/myself/"
METHOD = "GET"
QUERY_STRING = ""
REQUEST_BODY = "" # For GET requests, body is usually empty
def generate_signature(api_key_id, api_secret, path, query_string, request_body, nonce):
"""
Generates the HMAC-SHA256 signature for a Localbitcoins API request.
"""
# Construct the message string to be signed
# The order of elements in the message string is critical.
message = f"{nonce}{api_key_id}{path}{query_string}{request_body}"
# Encode the secret and message for HMAC
secret_bytes = api_secret.encode('utf-8')
message_bytes = message.encode('utf-8')
# Create the HMAC-SHA256 signature
signature = hmac.new(secret_bytes, message_bytes, hashlib.sha256).hexdigest()
return signature
def make_signed_request(api_key_id, api_secret, method, path, query_string="", request_body=""):
"""
Constructs and sends a signed request to the Localbitcoins API.
"""
# Generate a nonce (current Unix timestamp is a common choice)
nonce = str(int(time.time() * 1000))
# Generate the signature
signature = generate_signature(api_key_id, api_secret, path, query_string, request_body, nonce)
# Construct headers
headers = {
"Apiauth-Key": api_key_id,
"Apiauth-Nonce": nonce,
"Apiauth-Signature": signature,
"Content-Type": "application/x-www-form-urlencoded" # Or application/json if sending JSON body
}
# Construct the full URL
url = f"{BASE_URL}{PATH}"
if query_string:
url += f"?{query_string}"
print(f"Requesting URL: {url}")
print(f"Headers: {headers}")
print(f"Request Body: {request_body}")
# Send the request
try:
if method.upper() == "GET":
response = requests.get(url, headers=headers)
elif method.upper() == "POST":
response = requests.post(url, headers=headers, data=request_body)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
print(f"Response: {response.text}")
except requests.exceptions.RequestException as err:
print(f"Other request error occurred: {err}")
return None
# --- Example Usage ---
if __name__ == "__main__":
# To get details about your own account
print("Fetching 'myself' details...")
my_details = make_signed_request(API_KEY_ID, API_SECRET, METHOD, PATH)
if my_details:
print("My details:")
print(my_details)
# Example of a POST request (hypothetical, adjust path/body as per actual API)
# POST_PATH = "/api/ads/create/"
# POST_BODY = "account_info=bank_details&ad_type=SELL&amount=0.01&countrycode=US¤cy=USD&lat=0&lon=0&msg=Buy%20my%20Bitcoin!&online_provider=NATIONAL_BANK_TRANSFER&price=50000&trade_limit=100"
# print("\nAttempting hypothetical POST request...")
# post_response = make_signed_request(API_KEY_ID, API_SECRET, "POST", POST_PATH, request_body=POST_BODY)
# if post_response:
# print("POST Response:")
# print(post_response)
This example demonstrates the construction of the signature string, the use of hmac and hashlib for cryptographic processing, and packaging the necessary headers for a successful API call. Ensure that your API_KEY_ID and API_SECRET are replaced with your actual credentials. The nonce should always be a unique, monotonically increasing number for each request, typically a Unix timestamp in milliseconds.
Security best practices
Implementing robust security practices is paramount when interacting with any cryptocurrency API, especially one that handles financial transactions like Localbitcoins. Adhering to these best practices can mitigate common vulnerabilities and protect your accounts and funds:
- Secure Credential Storage: Never hardcode your API Key ID or API Secret directly into your application's source code. Use environment variables, a secure configuration management system, or a dedicated secret management service (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) to store and retrieve sensitive credentials. This prevents exposure if your code repository is compromised.
- Principle of Least Privilege: Grant your API keys only the minimum necessary permissions. If your application only needs to read account balances, do not give it trade execution permissions. This limits the damage an attacker can inflict if they gain access to your key. Periodically review and adjust permissions as your application's needs evolve.
- Rotate API Keys Regularly: Establish a routine for regenerating your API keys. While there's no universally prescribed frequency, rotating keys every 90-180 days is a common practice in enterprise security. This minimizes the window of exposure for any potentially compromised key. Immediately revoke and regenerate any key if you suspect it has been compromised.
- Use HTTPS for All Communications: Always ensure that all API requests are made over HTTPS. This encrypts the communication channel between your application and the Localbitcoins servers, preventing eavesdropping and man-in-the-middle attacks. All major API platforms, including Localbitcoins, enforce HTTPS.
- Validate Input and Output: Thoroughly validate all data sent to and received from the API. Malicious input can exploit vulnerabilities, and invalid output might indicate an issue with the API or a possible compromise. Sanitize user inputs before including them in API requests.
- Implement Error Handling and Logging: Implement comprehensive error handling to gracefully manage API failures or authentication errors. Log relevant (but non-sensitive) information about API calls, responses, and errors. This helps in debugging and identifying suspicious activity. Avoid logging sensitive information like API keys or full request signatures.
- Time-based Nonces: Ensure your nonce generation is robust and monotonically increasing. Using a timestamp (e.g., Unix milliseconds) is generally acceptable, but ensure your system's clock is synchronized to prevent issues with server-side nonce validation. Discrepancies can lead to legitimate requests being rejected.
- IP Whitelisting (if available): If Localbitcoins offers IP whitelisting for API keys, enable it. This restricts API access to only a predefined list of IP addresses, adding an extra layer of security. Even if a key is stolen, it cannot be used from an unauthorized IP address.
- Monitor API Usage: Regularly monitor your API usage logs for unusual activity, such as a sudden increase in requests, requests from unexpected IP addresses, or a high rate of failed authentication attempts. Anomalies could indicate a security incident.
- Stay Informed: Keep up-to-date with Localbitcoins's security advisories and API documentation updates. Security best practices evolve, and staying informed ensures your integrations remain secure. General API security standards can also provide valuable context.