clear_saved_tokens()

Remove all stored authentication tokens from local storage

Logout
Complete logout
Switch Accounts
Clean account switch
Security
Remove credentials
Testing
Clean test state

Overview

The clear_saved_tokens() method removes all securely stored authentication tokens from local storage. This is essential for logout operations, security cleanup, troubleshooting authentication issues, or when switching between different Axiom Trade accounts.

What Gets Deleted

This method deletes the encrypted token files stored in ~/.axiomtradeapi/, forcing the user to re-authenticate on the next API request.

Logout Operations

Complete user logout from your application

Account Switching

Clean transition between different accounts

Security Cleanup

Remove tokens in case of security concerns

Troubleshooting

Fix corrupted or invalid token issues

Method Signature

python
def clear_saved_tokens(self) -> bool

Parameters

None - This method takes no parameters.

Return Value

Returns a boolean indicating success or failure:

True

Tokens successfully cleared (or no tokens existed)

False

Failed to clear tokens (file system error, permissions, etc.)

How It Works

Storage Location

Tokens are stored in encrypted files at:

bash
~/.axiomtradeapi/
├── tokens.enc     # Encrypted authentication tokens
└── key.enc        # Encryption key

What Gets Deleted

When you call clear_saved_tokens():

  • Deletes ~/.axiomtradeapi/tokens.enc (encrypted token file)
  • Keeps ~/.axiomtradeapi/key.enc (encryption key remains for future use)
  • Clears in-memory token cache in the client instance

Security Implications

  • Safe to use: Tokens are removed from disk
  • Encryption key preserved: Future logins use same key
  • Requires re-authentication: Next API call needs login
  • Does not revoke tokens: Tokens may still be valid server-side until expiry

Basic Usage Examples

Example 1: Simple Logout

Clear tokens when user logs out of your application.

python
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()

# User logs in
client.login("username", "password")

# ... use API ...

# User logs out - clear stored tokens
if client.clear_saved_tokens():
    print("✅ Logged out successfully - tokens cleared")
else:
    print("âš ī¸ Warning: Failed to clear tokens")

Example 2: Check Before Clearing

Verify tokens exist before attempting to clear them.

python
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()

# Check if tokens are saved
if client.has_saved_tokens():
    print("📁 Saved tokens found - clearing...")
    
    if client.clear_saved_tokens():
        print("✅ Tokens cleared successfully")
    else:
        print("❌ Failed to clear tokens")
else:
    print("â„šī¸  No saved tokens to clear")

Example 3: Complete Logout Flow

Comprehensive logout that clears both session and saved tokens.

python
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()

def logout():
    """
    Complete logout: clear session and stored tokens
    """
    print("🔓 Logging out...")
    
    # 1. Call API logout endpoint (if authenticated)
    if client.is_authenticated():
        try:
            client.logout()
            print("   ✅ API logout successful")
        except Exception as e:
            print(f"   âš ī¸  API logout failed: {e}")
    
    # 2. Clear saved tokens from disk
    if client.clear_saved_tokens():
        print("   ✅ Local tokens cleared")
    else:
        print("   ❌ Failed to clear local tokens")
    
    # 3. Verify tokens are gone
    if not client.has_saved_tokens():
        print("✅ Logout complete - all tokens removed")
    else:
        print("âš ī¸ Warning: Some tokens may still remain")

# Perform logout
logout()

Advanced Examples

Advanced usage patterns for production applications:

Multi-Account Switching

Manage multiple Axiom Trade accounts

Auto Refresh Recovery

Clear corrupted tokens on failure

Security Audit & Cleanup

Periodic token age enforcement

Testing Environment Reset

Clean state for automated tests

Full advanced examples with complete code are available in the GitHub repository

View Examples on GitHub

Best Practices

1. Always Check Return Value

python
# ✅ Good: Check if clearing succeeded
if client.clear_saved_tokens():
    print("Tokens cleared successfully")
else:
    print("Failed to clear tokens - check permissions")
    # Handle error appropriately

# ❌ Bad: Ignore return value
client.clear_saved_tokens()  # Did it work? Unknown!

2. Clear on Logout

python
def logout_user():
    """Complete logout process"""
    # Call API logout
    client.logout()
    
    # Clear local tokens
    client.clear_saved_tokens()
    
    print("Logged out successfully")

3. Verify Tokens Are Gone

python
# Clear tokens
client.clear_saved_tokens()

# Verify
if not client.has_saved_tokens():
    print("✅ Tokens successfully removed")
else:
    print("âš ī¸ Tokens may still exist")

4. Use Context Manager

python
from contextlib import contextmanager

@contextmanager
def axiom_session(username, password, clear_on_exit=True):
    """Context manager for Axiom API session"""
    client = AxiomTradeClient()
    
    try:
        client.login(username, password)
        yield client
    finally:
        if clear_on_exit:
            client.clear_saved_tokens()
            print("Session tokens cleared")

# Usage
with axiom_session("user", "pass") as client:
    balance = client.GetBalance()
# Tokens automatically cleared here

Common Use Cases

User Logout

Clear tokens when user clicks logout button

python
def handle_logout_button():
    client.logout()
    client.clear_saved_tokens()
    redirect_to_login_page()

Account Switching

Switch between different accounts

python
def switch_account(new_user, new_pass):
    client.clear_saved_tokens()
    client.login(new_user, new_pass)

Security Timeout

Clear tokens after inactivity

python
TIMEOUT_SECONDS = 1800  # 30 min

def check_timeout():
    if time.time() - last_activity > TIMEOUT:
        client.clear_saved_tokens()

Troubleshooting Auth

Fix corrupted tokens

python
def fix_auth_issues():
    client.clear_saved_tokens()
    client.login(username, password)

Troubleshooting

Issue: clear_saved_tokens() Returns False

Problem: Method returns False, indicating failure to clear tokens.

Possible Causes:

  • â€ĸ File permissions issue
  • â€ĸ File locked by another process
  • â€ĸ Disk full
  • â€ĸ File system error
python
from pathlib import Path

# Check if token file exists
token_file = Path.home() / '.axiomtradeapi' / 'tokens.enc'

if token_file.exists():
    # Check permissions
    print(f"Permissions: {oct(token_file.stat().st_mode)}")
    
    # Try manual deletion
    try:
        token_file.unlink()
        print("✅ Manually deleted")
    except PermissionError:
        print("❌ Permission denied")
    except Exception as e:
        print(f"❌ Error: {e}")

Issue: Tokens Still Exist After Clearing

Problem: has_saved_tokens() returns True even after clear_saved_tokens().

python
from pathlib import Path

token_dir = Path.home() / '.axiomtradeapi'
token_file = token_dir / 'tokens.enc'

print(f"Token file exists: {token_file.exists()}")

# Force delete if needed
if token_file.exists():
    import os
    os.remove(token_file)
    print("✅ Forcefully removed")

Issue: Permission Denied on macOS/Linux

Solution: Fix file permissions

bash
# Check permissions
ls -la ~/.axiomtradeapi/

# Fix permissions
chmod 700 ~/.axiomtradeapi/
chmod 600 ~/.axiomtradeapi/tokens.enc

Need Help?

Our support team can help you troubleshoot token clearing issues

Security Considerations

Tokens May Still Be Valid

Clearing tokens locally doesn't invalidate them server-side. The tokens can still be used until they expire if someone else has a copy.

Encryption Key Remains

The key.enc file is NOT deleted. Future logins will use the same encryption key.

In-Memory Tokens

Clearing saved tokens doesn't clear tokens in the current client instance's memory. Use logout() for complete cleanup.

Complete Secure Logout

python
def secure_logout():
    """Complete secure logout procedure"""
    # 1. Server-side logout
    try:
        client.logout()
        print("✅ Server logout successful")
    except:
        print("âš ī¸ Server logout failed")
    
    # 2. Clear saved tokens
    if client.clear_saved_tokens():
        print("✅ Local tokens cleared")
    else:
        print("❌ Failed to clear tokens")
    
    # 3. Verify removal
    if not client.has_saved_tokens():
        print("✅ Verification passed")
    else:
        print("âš ī¸ Tokens still present")
    
    # 4. Clear in-memory state
    client.access_token = None
    client.refresh_token = None
    
    print("🔐 Secure logout complete")

Related Documentation

Build Secure Applications

Need help implementing secure authentication and token management? We're here to help.

Open Source

Contribute to AxiomTradeAPI

View on GitHub

Community

Join 1000+ developers

Join Discord

Custom Development

Professional bot building

Get Started