ensure_authenticated()

Intelligent authentication guard with automatic token refresh and recovery

Auto Validate
Token checking
Auto Refresh
Token renewal
Re-auth
Automatic recovery
Resilient
Complete lifecycle

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

python
def ensure_authenticated(self) -> bool

Parameters

None - This method takes no parameters.

Return Value

Returns a boolean indicating authentication status:

True

Valid authentication available (tokens valid or refreshed/renewed)

False

Authentication failed (no tokens, refresh failed, no credentials)

How It Works

Authentication Flow

ensure_authenticated() called
↓ Has tokens?
✓ Yes → Tokens valid?
✓ Yes → Return True
✗ No → Try refresh
✓ Refresh success → Return True
✗ Refresh failed → Re-authenticate
✗ No → Have credentials?
✓ Yes → Re-authenticate → Return True/False
✗ No → Return False

Internal Logic

  1. 1
    Check if tokens exist

    If no tokens: Try to authenticate with stored credentials. If no credentials: Return False

  2. 2
    Check if tokens are valid

    If tokens not expired: Return True. If tokens expired: Proceed to step 3

  3. 3
    Try to refresh tokens

    If refresh successful: Return True. If refresh failed: Proceed to step 4

  4. 4
    Try 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.

python
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.

python
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.

python
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 GitHub

Best Practices

1. Always Check Before API Calls

python
# ✅ 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 error

2. Initialize with Credentials for Auto-Recovery

python
# ✅ 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-authenticate

3. Use in Long-Running Applications

python
# ✅ 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

python
# ✅ 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

python
if not client.ensure_authenticated():
    return {"error": "Not authenticated"}

return client.GetBalance()

Trading Bot

Automated trading with auth checks

python
while trading_active:
    if not client.ensure_authenticated():
        logger.error("Bot stopped")
        break
    execute_trades()

Scheduled Tasks

Periodic operations

python
def scheduled_task():
    if client.ensure_authenticated():
        send_balance_report()
    else:
        send_alert("Auth failed")

Health Check

System health monitoring

python
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
python
# 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.

python
# 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

python
# 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 checked

Need 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.

Open Source

Contribute to AxiomTradeAPI

View on GitHub

Community

Join 1000+ developers

Join Discord

Custom Development

Professional bot building

Get Started