Authentication overview
GetOTP provides a programmatic interface for generating and verifying one-time passwords (OTPs), primarily through its REST API. To ensure that only authorized applications can interact with the service, GetOTP employs authentication mechanisms that identify the calling application and verify its permissions. The core authentication strategy relies on API keys, which are unique identifiers issued to developers or applications. For operations requiring a higher level of assurance regarding data integrity and sender verification, GetOTP also supports HMAC (Hash-based Message Authentication Code) signing of requests.
The authentication process typically involves including your credentials in the header of each API request. This approach is standard for many RESTful APIs, where authentication tokens or keys are passed with every interaction to maintain a stateless connection while securing access to resources. Proper management and protection of these credentials are crucial to prevent unauthorized access to your GetOTP account and the OTP services it provides to your users.
Developers integrating with GetOTP can leverage official SDKs for languages such as Python, Node.js, and Java, which abstract away some of the complexities of handling authentication headers and request signing. These SDKs are designed to streamline the integration process and help developers implement secure OTP workflows efficiently, as detailed in the GetOTP documentation.
Supported authentication methods
GetOTP supports two primary methods for authenticating API requests, each designed for different levels of security and integration complexity.
- API Key Authentication: This is the most common method for authenticating with GetOTP. An API key is a unique string that identifies your application. It is typically passed in the HTTP
Authorizationheader of your requests. This method is suitable for most applications where the primary concern is to identify the caller and ensure they have the necessary permissions to access GetOTP services. API keys should be treated as sensitive credentials, similar to passwords, and protected accordingly. - HMAC Request Signing: For enhanced security, particularly in scenarios where message integrity and sender authenticity are critical, GetOTP supports HMAC-based request signing. HMAC uses a secret key, known only to your application and GetOTP, to create a cryptographic hash of the request payload and certain headers. This hash is then included in the request. GetOTP can re-calculate the HMAC using its copy of the secret key and compare it with the one provided in the request. Any discrepancy indicates that the request has been tampered with or was not sent by an authorized party. This method provides protection against replay attacks and data manipulation, offering a higher level of assurance than API key authentication alone. The IETF RFC 2104 defines the HMAC algorithm standard.
The choice between these methods depends on your application's specific security requirements. API key authentication offers simplicity and is sufficient for many use cases, while HMAC signing provides a robust mechanism for verifying the authenticity and integrity of each request.
Authentication Methods Comparison
| Method | When to Use | Security Level |
|---|---|---|
| API Key Authentication | Standard API access, quick integration, internal services | Moderate (protects against unauthorized access) |
| HMAC Request Signing | High-security transactions, public-facing APIs, sensitive data, anti-tampering | High (protects against unauthorized access, tampering, and replay attacks) |
Getting your credentials
To begin using GetOTP's API, you will need to obtain your API key and, if using HMAC, your secret key. These credentials are generated and managed through your GetOTP dashboard.
- Sign Up/Log In: First, navigate to the GetOTP homepage and either sign up for a new account or log in to your existing one. GetOTP offers a Developer Plan with 500 free authentications per month to get started.
- Access Dashboard: Once logged in, you will be redirected to your developer dashboard.
- Locate API Keys: Within the dashboard, there is typically a section dedicated to API Keys or Security Settings. The exact navigation may vary, but it's usually clearly labeled. Refer to the GetOTP API reference for precise instructions on locating these settings within the dashboard.
- Generate Credentials: You will find your primary API key listed here. For HMAC signing, you may need to generate a separate secret key or use a provided one associated with your API key. It is common practice for platforms to allow the generation of multiple API keys, enabling you to revoke specific keys without affecting others, which is useful for different environments (e.g., development, staging, production) or different applications.
- Secure Storage: Once generated, copy your API key and secret key (if applicable) and store them securely. They should never be hardcoded directly into your application's source code, committed to version control systems, or exposed in client-side code.
It is recommended to rotate your API keys periodically and to immediately revoke any keys that may have been compromised. The GetOTP dashboard provides tools to manage these credentials, including the ability to generate new keys and revoke old ones.
Authenticated request example
Here's an example of how to make an authenticated request to GetOTP's API using an API key in the Authorization header. This Python example uses the requests library to send a POST request to generate an OTP.
import requests
import json
API_KEY = "YOUR_GETOTP_API_KEY" # Replace with your actual API key
API_BASE_URL = "https://api.getotp.io/v1"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
# Example: Generate an OTP for a phone number
payload = {
"phone_number": "+15551234567",
"channel": "sms" # or "email"
}
response = requests.post(f"{API_BASE_URL}/otp/generate", headers=headers, data=json.dumps(payload))
if response.status_code == 200:
print("OTP generation successful:")
print(json.dumps(response.json(), indent=2))
else:
print(f"Error generating OTP: {response.status_code}")
print(response.text)
For HMAC-signed requests, the process involves computing a signature based on the request content and a shared secret, then including this signature in a specific header, often X-GetOTP-Signature or similar. The exact steps for HMAC signing, including the canonicalization of headers and payload, are detailed in the GetOTP HMAC signing documentation.
import hmac
import hashlib
import time
import base64
import requests
import json
API_KEY = "YOUR_GETOTP_API_KEY"
SECRET_KEY = "YOUR_GETOTP_SECRET_KEY" # Secret key for HMAC signing
API_BASE_URL = "https://api.getotp.io/v1"
# Example: Generate an OTP for a phone number with HMAC signing
endpoint = "/otp/generate"
method = "POST"
payload_data = {
"phone_number": "+15551234567",
"channel": "sms"
}
body = json.dumps(payload_data, separators=(',', ':')) # Ensure no whitespace for hashing
timestamp = str(int(time.time()))
# Construct the string to sign
string_to_sign = f"{method}\n{endpoint}\n{timestamp}\n{body}"
# Calculate HMAC signature
signature = hmac.new(SECRET_KEY.encode('utf-8'), string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
"X-GetOTP-Timestamp": timestamp,
"X-GetOTP-Signature": signature
}
response = requests.post(f"{API_BASE_URL}{endpoint}", headers=headers, data=body)
if response.status_code == 200:
print("OTP generation with HMAC successful:")
print(json.dumps(response.json(), indent=2))
else:
print(f"Error generating OTP with HMAC: {response.status_code}")
print(response.text)
Security best practices
Securing your GetOTP integration is paramount to protecting your users and your application. Adhering to these best practices can mitigate common security risks:
- Treat API Keys as Sensitive: Your API keys grant access to your GetOTP account. Never expose them in client-side code (e.g., JavaScript in a browser), commit them to public version control repositories (like GitHub), or hardcode them directly into your application. Instead, use environment variables, secret management services, or configuration files that are not publicly accessible.
- Use Environment Variables: Store API keys and secret keys as environment variables on your server or in your deployment environment. This keeps them out of your codebase and allows for easy rotation without code changes.
- Implement Least Privilege: If GetOTP offers different types of API keys with varying permissions, generate keys with the minimum necessary permissions for each application or service. This limits the potential damage if a key is compromised.
- Rotate Credentials Regularly: Periodically rotate your API keys and secret keys. This reduces the window of opportunity for an attacker to use a compromised key. The GetOTP dashboard supports key rotation.
- Utilize HMAC Signing for Critical Operations: For any operations involving sensitive user data or financial transactions, or when your application is exposed to potential tampering, use HMAC request signing. This adds a layer of integrity checking and sender authentication, making it much harder for attackers to forge or alter requests. Twilio, for example, also recommends webhook security measures like request signing to protect against similar threats, as outlined in their Twilio webhook security guide.
- Secure Your Server Environment: Ensure that the server or environment where your GetOTP integration runs is secure. This includes keeping operating systems and software up to date, using strong access controls, and implementing network security measures (e.g., firewalls).
- Monitor API Usage: Regularly monitor your GetOTP API usage logs for any unusual activity. Spikes in OTP generation or verification requests, especially during off-peak hours, could indicate a compromised key or an attack.
- Implement Rate Limiting: Implement rate limiting on your own application's endpoints that interact with GetOTP. This helps prevent abuse, such as attackers attempting to flood users with OTPs or brute-forcing OTP verification codes.
- HTTPS Everywhere: Always ensure all communication with the GetOTP API occurs over HTTPS. This encrypts data in transit, protecting your API keys and request payloads from eavesdropping.
- Error Handling and Logging: Implement robust error handling and logging for all GetOTP API interactions. This helps in debugging issues and identifying potential security incidents. However, be careful not to log sensitive information like API keys or full request/response bodies in plain text.