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
def clear_saved_tokens(self) -> boolParameters
None - This method takes no parameters.
Return Value
Returns a boolean indicating success or failure:
TrueTokens successfully cleared (or no tokens existed)
FalseFailed to clear tokens (file system error, permissions, etc.)
How It Works
Storage Location
Tokens are stored in encrypted files at:
~/.axiomtradeapi/
âââ tokens.enc # Encrypted authentication tokens
âââ key.enc # Encryption keyWhat 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.
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.
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.
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 GitHubBest Practices
1. Always Check Return Value
# â
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
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
# 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
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 hereCommon Use Cases
User Logout
Clear tokens when user clicks logout button
def handle_logout_button():
client.logout()
client.clear_saved_tokens()
redirect_to_login_page()Account Switching
Switch between different accounts
def switch_account(new_user, new_pass):
client.clear_saved_tokens()
client.login(new_user, new_pass)Security Timeout
Clear tokens after inactivity
TIMEOUT_SECONDS = 1800 # 30 min
def check_timeout():
if time.time() - last_activity > TIMEOUT:
client.clear_saved_tokens()Troubleshooting Auth
Fix corrupted tokens
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
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().
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
# Check permissions
ls -la ~/.axiomtradeapi/
# Fix permissions
chmod 700 ~/.axiomtradeapi/
chmod 600 ~/.axiomtradeapi/tokens.encNeed 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
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.