Overview
The ensure_authenticated() method is an intelligent authentication guard that automatically ensures you have valid authentication tokens before making API requests. It handles token validation, automatic refresh, and re-authentication seamlessly, providing a robust authentication layer for your application.
Recommended Method
This is the recommended way to verify authentication status before performing API operations, as it handles the complete authentication lifecycle automatically.
Automatic Validation
Checks if current tokens are valid
Automatic Refresh
Refreshes expired tokens automatically
Re-authentication
Re-authenticates if refresh fails
Resilient Design
Handles complete auth lifecycle
Method Signature
def ensure_authenticated(self) -> boolParameters
None - This method takes no parameters.
Return Value
Returns a boolean indicating authentication status:
TrueValid authentication available (tokens valid or refreshed/renewed)
FalseAuthentication failed (no tokens, refresh failed, no credentials)
How It Works
Authentication Flow
Internal Logic
- 1Check if tokens exist
If no tokens: Try to authenticate with stored credentials. If no credentials: Return False
- 2Check if tokens are valid
If tokens not expired: Return True. If tokens expired: Proceed to step 3
- 3Try to refresh tokens
If refresh successful: Return True. If refresh failed: Proceed to step 4
- 4Try to re-authenticate
If credentials available: Re-authenticate. If no credentials: Return False
Basic Usage Examples
Example 1: Simple Authentication Check
Check if authenticated before making API calls.
from axiomtradeapi import AxiomTradeClient
client = AxiomTradeClient()
# Login
client.login("username", "password")
# Verify authentication
if client.ensure_authenticated():
print("✅ Authenticated - safe to make API calls")
balance = client.GetBalance()
print(f"Balance: {balance['sol']} SOL")
else:
print("❌ Not authenticated - please login")Example 2: Automatic Re-authentication
ensure_authenticated() automatically handles expired tokens.
from axiomtradeapi import AxiomTradeClient
import time
# Initialize with credentials for auto re-authentication
client = AxiomTradeClient(username="user", password="pass")
# First call - tokens are valid
if client.ensure_authenticated():
print("✅ First check: Authenticated")
# Simulate time passing (tokens might expire)
time.sleep(2)
# Second call - will auto-refresh if needed
if client.ensure_authenticated():
print("✅ Second check: Still authenticated")
print(" (Tokens automatically refreshed if needed)")
else:
print("❌ Authentication failed")Example 3: Guard API Calls
Use as a guard before every API operation.
from axiomtradeapi import AxiomTradeClient
def get_balance_safely(client):
"""Safely get balance with authentication check"""
if not client.ensure_authenticated():
return {"error": "Authentication required"}
try:
return client.GetBalance()
except Exception as e:
return {"error": str(e)}
# Usage
client = AxiomTradeClient()
client.login("username", "password")
balance = get_balance_safely(client)
if "error" in balance:
print(f"❌ Error: {balance['error']}")
else:
print(f"✅ Balance: {balance['sol']} SOL")Advanced Examples
Advanced usage patterns for production applications:
Re-authentication Wrapper
Decorator for automatic auth checks
Session Management
Health checks for long-running apps
Retry Logic
Automatic recovery from failures
Multi-Client Manager
Manage multiple authenticated clients
Full advanced examples with complete code are available in the GitHub repository
View Examples on GitHubBest Practices
1. Always Check Before API Calls
# ✅ Good: Check authentication first
if client.ensure_authenticated():
balance = client.GetBalance()
else:
print("Authentication required")
# ❌ Bad: Assume you're authenticated
balance = client.GetBalance() # May fail with auth error2. Initialize with Credentials for Auto-Recovery
# ✅ Good: Credentials enable auto-recovery
client = AxiomTradeClient(username="user", password="pass")
# ensure_authenticated() can auto re-authenticate if tokens expire
# ⚠️ Less Resilient: No credentials for recovery
client = AxiomTradeClient()
client.set_tokens(access_token, refresh_token)
# ensure_authenticated() can only refresh, not re-authenticate3. Use in Long-Running Applications
# ✅ Good: Periodic checks in long-running apps
while True:
if client.ensure_authenticated():
# Do work
balance = client.GetBalance()
else:
print("Re-authentication needed")
break
time.sleep(60)4. Combine with Error Handling
# ✅ Good: Comprehensive error handling
try:
if not client.ensure_authenticated():
raise ValueError("Authentication failed")
balance = client.GetBalance()
except ValueError as e:
print(f"Auth error: {e}")
except Exception as e:
print(f"API error: {e}")Common Use Cases
API Request Guard
Protect every API call
if not client.ensure_authenticated():
return {"error": "Not authenticated"}
return client.GetBalance()Trading Bot
Automated trading with auth checks
while trading_active:
if not client.ensure_authenticated():
logger.error("Bot stopped")
break
execute_trades()Scheduled Tasks
Periodic operations
def scheduled_task():
if client.ensure_authenticated():
send_balance_report()
else:
send_alert("Auth failed")Health Check
System health monitoring
def check_health():
return {
"auth": client.ensure_authenticated(),
"api": test_connection()
}Troubleshooting
Issue: Always Returns False
Problem: ensure_authenticated() consistently returns False.
Possible Causes:
- • No tokens and no credentials provided
- • Invalid credentials
- • Network connectivity issues
- • Refresh token expired
# Check if client has credentials
client = AxiomTradeClient(username="user", password="pass")
# Verify credentials
if not client.ensure_authenticated():
print("Check credentials")
# Try manual login to see error
try:
client.login("username", "password")
except Exception as e:
print(f"Login error: {e}")Issue: Repeated Re-authentication
Problem: Client keeps re-authenticating instead of refreshing tokens.
# Check token status
token_info = client.get_token_info_detailed()
print(f"Token expired: {token_info.get('is_expired')}")
print(f"Needs refresh: {token_info.get('needs_refresh')}")
# Verify refresh token
if client.refresh_token:
print("Refresh token: Available")
else:
print("Refresh token: None - will re-auth")Issue: Performance Degradation
Solution: Cache authentication checks
# Cache authentication checks
last_check = 0
CHECK_INTERVAL = 60
def check_auth_cached():
global last_check
current = time.time()
if current - last_check > CHECK_INTERVAL:
is_auth = client.ensure_authenticated()
last_check = current
return is_auth
return True # Skip if recently checkedNeed Help?
Our support team can help you troubleshoot authentication issues
Related Documentation
Build Resilient Applications
Need help implementing robust authentication? Our team can assist you.