Advanced Authentication Patterns — OAuth 2.0, JWT, Key Rotation

Master sophisticated authentication mechanisms for integrating Smart Money API in enterprise environments. Learn OAuth 2.0 flows, JWT token patterns, secure key rotation, and multi-factor authentication implementation.

Published March 21, 2026 18 min read Advanced

Authentication Overview

The Smart Money API supports multiple authentication methods designed to accommodate different application architectures, security requirements, and organizational policies. Understanding these patterns ensures your integration is both secure and performant.

Authentication in the Smart Money API operates across three primary layers:

  • API Keys — Simple bearer token authentication for development and straightforward integrations
  • JWT Tokens — Stateless, cryptographically signed tokens for distributed systems and microservices
  • OAuth 2.0 — Delegated authorization framework for third-party integrations and SaaS applications

Security Principle: Never expose authentication credentials in client-side code, logs, version control, or error messages. Implement credential rotation on a schedule and immediately upon compromise.

Each method has distinct advantages. API keys work best for backend-to-backend communication where credential storage is controlled. JWT tokens excel in distributed architectures where no shared state is available. OAuth 2.0 provides user-delegated access for third-party applications.

API Key Authentication

API keys are the simplest authentication mechanism—they're random strings generated for your account that identify your application to the Smart Money API. Every request must include your API key either as a header or query parameter.

Header-Based API Key

The recommended approach is passing your API key in the Authorization header using the Bearer scheme:

curl Example
curl -X GET "https://api.smartmoneyapi.com/v1/whales/btc" \
-H "Authorization: Bearer sk_live_1234567890abcdef" \
-H "Accept: application/json"

Query Parameter API Key

For WebSocket connections or when headers cannot be modified, pass the API key as a query parameter:

WebSocket Connection
ws://localhost:8877/ws?api_key=sk_live_1234567890abcdef
// Establishes authenticated WebSocket stream

API Key Characteristics

Property Description
Format 128-character hex string prefixed with sk_test_ or sk_live_
Scope Inherits all permissions of the account that created it
Expiration Never expires automatically; must be rotated manually
Rotation Generate new key, migrate traffic, then deactivate old key
Rate Limits Shared across all requests using the same key

API Key Security Practices

  • Environment Variables — Store keys in .env files (not committed to version control) and load at runtime
  • Vault Systems — Use HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault in production
  • Separate Keys — Maintain separate test and live keys; rotate test keys frequently
  • Minimal Scope — Create separate keys for different integrations when possible
  • Audit Logging — Log all API key creation and usage events
Get your API key in 30 seconds

Ready to build? Grab a free API key (200 calls/day, no card) and start pulling live whale, funding and on-chain data.

Get your API key →

Bearer Token Pattern

Bearer tokens extend the simple API key concept by adding context, expiration, and refresh mechanisms. They're ideal for applications that need programmatic credential management.

Obtaining Bearer Tokens

Exchange your API key and secret for a bearer token valid for 24 hours:

GET /auth/token
curl -X POST "https://api.smartmoneyapi.com/v1/auth/token" \
-H "Content-Type: application/json" \
-d '{
"api_key": "sk_live_1234567890",
"api_secret": "secret_abc123xyz"
}'

Token Response Format

The endpoint returns a bearer token with metadata:

Response
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 86400,
"refresh_token": "refresh_1234567..."
}

Using Bearer Tokens

Include the token in the Authorization header for all subsequent requests:

Authenticated Request
curl -X GET "https://api.smartmoneyapi.com/v1/derivatives/funding-heatmap" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

Token Refresh Flow

When a token approaches expiration, use the refresh token to obtain a new one without requiring your API secret:

POST /auth/refresh
curl -X POST "https://api.smartmoneyapi.com/v1/auth/refresh" \
-H "Content-Type: application/json" \
-d '{
"refresh_token": "refresh_1234567..."
}'

OAuth 2.0 Implementation

OAuth 2.0 enables users to grant applications access to their Smart Money API accounts without sharing credentials. This is essential for SaaS platforms, third-party integrations, and multi-tenant applications.

OAuth 2.0 Authorization Code Flow

The standard flow for web applications:

  1. User Initiates Login — User clicks "Connect with Smart Money API"
  2. Redirect to Authorization Server — Your app redirects user to Smart Money's authorization endpoint
  3. User Grants Permission — User reviews requested scopes and grants access
  4. Authorization Code Returned — User redirected back with authorization code
  5. Exchange Code for Token — Backend exchanges code for access token (code never exposed to frontend)
  6. Store Token — Store refresh token securely; use access token for API calls

Step 1: Redirect User to Authorization Endpoint

Frontend Redirect
// URL to redirect user to
const authUrl = new URL('https://api.smartmoneyapi.com/oauth/authorize');
authUrl.searchParams.append('client_id', 'your_client_id');
authUrl.searchParams.append('redirect_uri', 'https://yourapp.com/callback');
authUrl.searchParams.append('response_type', 'code');
authUrl.searchParams.append('scope', 'whales derivatives onchain');
authUrl.searchParams.append('state', generateRandomState());
window.location.href = authUrl.toString();

Step 2: Handle Callback and Exchange Code

Backend Code Exchange
// Backend handles /callback route
const code = req.query.code;
const storedState = req.session.state;
const receivedState = req.query.state;
// Verify state parameter
if (storedState !== receivedState) {
throw new Error('State mismatch - CSRF attack detected');
}
// Exchange code for token
const tokenResponse = await fetch('https://api.smartmoneyapi.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'authorization_code',
code: code,
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET,
redirect_uri: 'https://yourapp.com/callback'
})
});
const tokens = await tokenResponse.json();
// Store tokens securely

OAuth Scopes

Request only the scopes your application needs. Smart Money API defines these scopes:

Scope Description
whales Access whale wallet tracking and accumulation metrics
derivatives Access futures, perpetuals, and funding rate data
onchain Access on-chain transaction flows and analytics
alerts Create and manage webhook alerts
offline Access refresh tokens to obtain new access tokens offline

JWT Token Management

JWT (JSON Web Tokens) provide stateless authentication—the server doesn't need to store session data. Smart Money API uses RS256 (RSA Signature with SHA-256) for token signing, allowing verification without contacting the API.

JWT Structure

JWT tokens consist of three parts separated by dots:

JWT Format
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEifQ.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFjY3QxMjM0In0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
// HEADER.PAYLOAD.SIGNATURE

JWT Header

The header identifies the algorithm and token type:

Decoded Header
{
"alg": "RS256",
"typ": "JWT",
"kid": "1"
}

JWT Payload Claims

The payload contains claims (statements about the user/app):

Decoded Payload
{
"sub": "acct_1234567890",
"name": "Trading Bot",
"iat": 1703001600,
"exp": 1703088000,
"scopes": ["whales", "derivatives"],
"aud": "https://api.smartmoneyapi.com"
}

Verifying JWT Signatures

Download Smart Money's public key and verify tokens before accepting them:

Node.js Verification
const jwt = require('jsonwebtoken');
const fs = require('fs');
// Get public key from Smart Money API
const publicKey = fs.readFileSync('smartmoney-public.pem');
// Verify token
try {
const decoded = jwt.verify(token, publicKey, {
algorithms: ['RS256'],
audience: 'https://api.smartmoneyapi.com',
issuer: 'https://api.smartmoneyapi.com'
});
// Token is valid, use decoded claims
} catch (err) {
// Token invalid or expired
}

Key Rotation Strategy

Regular key rotation is critical for maintaining security. Even with perfect security practices, assume keys can be compromised and implement systematic rotation.

Rotation Frequency

Smart Money recommends different rotation schedules based on key type and usage:

Key Type Recommended Rotation Minimum Rotation
Test API Keys Monthly Quarterly
Production API Keys Quarterly Annually
OAuth Refresh Tokens Automatic (after 90 days) Manual (after 180 days)
Service Account Keys Semi-annually Annually

Zero-Downtime Rotation Process

Rotate keys without interrupting service:

  1. Generate New Key — Create new API key through dashboard or API
  2. Deploy New Key — Update application secrets in staging, test thoroughly
  3. Gradual Rollout — Deploy to 10% of servers, monitor for errors
  4. Full Rollout — Deploy to remaining servers
  5. Verify Traffic — Confirm all requests use new key
  6. Deactivate Old Key — Mark old key as inactive but don't delete immediately
  7. Delete Old Key — After 48 hours with no errors, permanently delete

Emergency Key Rotation

If you suspect a key is compromised:

Emergency Rotation
// Immediate action: Deactivate compromised key
curl -X POST "https://api.smartmoneyapi.com/v1/keys/sk_live_xxx/revoke" \
-H "Authorization: Bearer token"
// Generate replacement key immediately
curl -X POST "https://api.smartmoneyapi.com/v1/keys" \
-H "Content-Type: application/json" \
-d '{
"name": "Emergency Replacement Key"
}'

Automated Rotation in Kubernetes

Use Kubernetes Secrets and operators for automatic rotation:

CronJob for Key Rotation
apiVersion: batch/v1
kind: CronJob
metadata:
name: api-key-rotator
spec:
schedule: "0 0 * * 0" # Weekly on Sunday
jobTemplate:
spec:
template:
spec:
containers:
- name: rotator
image: smartmoney-key-rotator:latest

Multi-Factor Authentication (MFA)

For accounts accessing production data, MFA provides an additional security layer by requiring a second factor beyond just credentials.

MFA Methods Supported

  • TOTP (Time-based One-Time Password) — Apps like Google Authenticator, Authy
  • WebAuthn/FIDO2 — Hardware security keys, biometrics
  • SMS One-Time Codes — Less secure but universally supported
  • Email Confirmation — Confirmation codes sent to registered email

Enabling TOTP for Account Access

Enable MFA
// Step 1: Request MFA setup
curl -X POST "https://api.smartmoneyapi.com/v1/account/mfa/enable" \
-H "Authorization: Bearer token"
// Response includes QR code URL
{
"qr_code_url": "https://...",
"secret": "JBSWY3DPEBLW64TMMQ...",
"backup_codes": ["12345678", ...]
}

MFA During API Operations

Some operations may require MFA confirmation even after authentication:

MFA Challenge
// Attempting sensitive operation (key rotation)
curl -X POST "https://api.smartmoneyapi.com/v1/keys/rotate" \
-H "Authorization: Bearer token" \
-H "X-MFA-Token: mfa_challenge_abc123"
// Response: MFA required
{
"error": "mfa_required",
"mfa_token": "mfa_xyz789"
}
// Retry with TOTP code
curl -X POST "https://api.smartmoneyapi.com/v1/keys/rotate" \
-H "Authorization: Bearer token" \
-H "X-MFA-Code: 123456"

Security Best Practices

Authentication is only as strong as its implementation. Follow these practices to maintain security:

Secrets Management

  • Never commit secrets to version control — Use .env files with .gitignore
  • Use environment variables — Load from secure secret management systems
  • Scan repositories — Use tools like TruffleHog, detect-secrets to find exposed keys
  • Audit access logs — Monitor who accessed secrets and when

Transport Security

  • Always use HTTPS — Never send credentials over unencrypted connections
  • Verify SSL certificates — Don't disable certificate validation in production
  • Use certificate pinning — For mobile apps, prevent MITM attacks
  • Enforce TLS 1.2+ — Disable older protocols

Credential Handling

  • Hash secrets — Store bcrypt or Argon2 hashes, never plaintext
  • Minimize lifetime — Keep credentials in memory only as long as needed
  • Clear sensitive data — Explicitly overwrite credentials after use
  • Use secure libraries — Don't implement cryptography yourself

Logging and Monitoring

  • Never log credentials — Redact keys in logs, use log masking
  • Log authentication events — Track successful and failed login attempts
  • Monitor for anomalies — Alert on unusual access patterns
  • Audit key usage — Track which keys accessed what data

Enterprise Authentication Patterns

Large organizations often require additional security controls and compliance capabilities.

SAML 2.0 Integration

For enterprise customers, Smart Money API supports SAML 2.0 integration with your organization's identity provider (Okta, Azure AD, etc.):

  • Single Sign-On (SSO) — Users authenticate through your corporate IdP
  • Automatic provisioning — Create/disable accounts based on group membership
  • Enforcement — Require SAML for all user access

IP Whitelisting

Restrict API access to specific IP addresses or CIDR ranges:

IP Whitelist Management
// Add IP to whitelist
curl -X POST "https://api.smartmoneyapi.com/v1/account/ip-whitelist" \
-H "Authorization: Bearer token" \
-d '{
"cidr": "203.0.113.0/24",
"description": "Production servers"
}'

Audit Logging and Compliance

Enterprise plans include comprehensive audit logs for compliance:

Event Logged Data
Authentication User, timestamp, success/failure, IP, MFA status
Key Operations Key ID, action, initiator, timestamp
Account Changes What changed, who changed it, timestamp, before/after values
Data Access User, endpoint, scopes, timestamp, record count

Troubleshooting Authentication Issues

Invalid API Key Error

Problem: Receiving "401 Unauthorized - Invalid API Key"

Solutions:

  • Verify key format (should start with sk_test_ or sk_live_)
  • Check for trailing/leading whitespace in key
  • Confirm key hasn't been deactivated or rotated
  • Verify you're using the correct environment (test key for test, live for production)
  • Check API key permissions match endpoint requirements

Token Expired Error

Problem: Bearer token expired, requests failing

Solutions:

  • Use refresh token to obtain new access token
  • Implement automatic token refresh 5 minutes before expiration
  • Store refresh token securely (not in localStorage for SPAs)
  • Handle 401 responses by attempting refresh token flow

CORS/Preflight Errors

Problem: Browser blocking requests with CORS error

Solutions:

  • API calls from browsers must come from whitelisted origins
  • Add your domain via dashboard: Settings → CORS Origins
  • Browser sends OPTIONS preflight request automatically
  • For development, use localhost:3000 or similar

MFA Challenge Not Completing

Problem: Operations requiring MFA fail even with correct code

Solutions:

  • Ensure server clock is synchronized (TOTP relies on time)
  • Code is valid only for 30 seconds, generate new one
  • Use backup codes if authenticator app is unavailable
  • Account recovery available via registered email

Implement Secure Authentication Today

Smart Money API supports enterprise-grade authentication with OAuth 2.0, JWT, MFA, and SAML integration. Secure your API integration with industry best practices.

View Enterprise Plans
Need SAML, IP whitelisting, or dedicated support? Contact our sales team.

Related Resources

Start free — 200 calls/day, no card

Get live whale flow, funding, open interest and on-chain data across 3 exchanges from one API. Free tier, no credit card, upgrade any time.

Start free →
Try the live API console → (no account needed)