Skip to content

Token Management

Learn how Scalekit manages access tokens, refresh tokens, and token lifecycle for Agent Auth connections.

Token management is a critical aspect of Agent Auth that ensures your users’ connections remain active and secure. Scalekit automatically handles the complete token lifecycle, including storage, refresh, and expiration, so you can focus on building your application.

When users authenticate with third-party providers through Agent Auth, Scalekit securely manages several types of tokens:

Access tokens are short-lived credentials used to make authenticated API requests to third-party providers on behalf of users.

Characteristics:

  • Lifetime: Typically 1-2 hours (varies by provider)
  • Purpose: Authorize API requests to provider endpoints
  • Security: Encrypted at rest and in transit
  • Usage: Automatically included in tool execution requests

Refresh tokens are long-lived credentials used to obtain new access tokens when they expire.

Characteristics:

  • Lifetime: Typically 30-90 days or indefinite (varies by provider)
  • Purpose: Obtain new access tokens without user re-authentication
  • Security: Encrypted and stored securely by Scalekit
  • Usage: Automatically used when access tokens expire

Additional information stored with tokens:

  • Expiration time: When the access token expires
  • Granted scopes: Permissions the user granted
  • Provider account ID: User’s identifier with the provider
  • Token type: OAuth 2.0, API key, Bearer token, etc.

Scalekit automatically handles token refresh to ensure uninterrupted service for your users.

  1. Token expiration detection - Scalekit monitors token expiration times
  2. Proactive refresh - Tokens are refreshed 5 minutes before expiration
  3. Transparent refresh - Refresh happens without interrupting tool execution
  4. Status update - Connected account status updated upon successful refresh
  5. Error handling - Failed refreshes trigger appropriate error states
Token Lifecycle and RefreshUserScalekitProvider Authenticate OAuth Flow Access Token (expires in 1h) Connection Active Monitor expiration (55 min) Refresh access token New Access Token (expires in 1h) Update token, reset timer

When you execute a tool, Scalekit automatically handles token refresh if needed:

# You don't need to check token expiration manually
result = actions.execute_tool(
identifier="user_123",
tool_name='gmail_send_email',
tool_input={
'to': 'recipient@example.com',
'subject': 'Hello',
'body': 'This is a test email'
}
)
# Scalekit automatically:
# 1. Checks if access token is valid
# 2. Refreshes token if expired or expiring soon
# 3. Executes the tool with valid token
# 4. Returns result or error

While Scalekit handles automatic refresh, you can manually refresh tokens when needed:

Verify the current token status before manual operations:

# Get connected account details
account = actions.get_connected_account(
identifier="user_123",
connection_name="gmail"
)
# Check account status
if account.status == "ACTIVE":
print("✓ Tokens are valid")
elif account.status == "EXPIRED":
print("⚠ Tokens expired, refresh needed")
elif account.status == "REVOKED":
print("✗ User revoked access, re-authentication needed")

Manually trigger a token refresh when needed:

# Manually refresh tokens
try:
account = actions.refresh_connected_account(
identifier="user_123",
connection_name="gmail"
)
print(f"✓ Tokens refreshed successfully")
print(f" Status: {account.status}")
except Exception as e:
print(f"✗ Token refresh failed: {e}")
# Handle refresh failure - may need user re-authentication

Understanding how different scenarios affect token expiration:

Timeline:

  1. Access token issued (expires in 1 hour)
  2. Scalekit monitors expiration (55 minutes elapsed)
  3. Automatic refresh initiated (5 minutes before expiry)
  4. New access token obtained (valid for 1 hour)
  5. Cycle repeats

When refresh fails:

  • Revoked refresh token: User revoked app access
  • Invalid refresh token: Token became invalid or expired
  • Provider errors: Temporary provider API issues
  • Network issues: Connection problems during refresh

Scalekit behavior:

  • Account status changes to EXPIRED or REVOKED
  • Tool execution attempts return authentication errors
  • You receive detailed error information
  • User must re-authenticate to restore access

Implement proper error handling for refresh failures:

# Execute tool with refresh failure handling
try:
result = actions.execute_tool(
identifier="user_123",
tool_name='gmail_send_email',
tool_input={'to': 'user@example.com', 'subject': 'Hello', 'body': 'Test'}
)
except Exception as e:
# Check if error is due to token issues
if 'EXPIRED' in str(e) or 'REVOKED' in str(e):
# Get fresh authorization link for user
link_response = actions.get_authorization_link(
connection_name="gmail",
identifier="user_123"
)
# Notify user to re-authenticate
print(f"⚠ Please re-authenticate: {link_response.link}")
# In production: send email, push notification, or in-app message
else:
# Handle other errors
print(f"✗ Tool execution failed: {e}")

Scalekit implements multiple security measures to protect user tokens:

  • At rest: All tokens encrypted using AES-256
  • In transit: TLS 1.3 for all API communication
  • Key management: Regular key rotation and secure storage
  • Access control: Role-based access to token data
  • User isolation: Each user’s tokens stored separately
  • Tenant isolation: Multi-tenant architecture with data separation
  • Connection isolation: Different connections use different tokens
  • Audit trail: Complete logging of token access

Scalekit’s token management meets industry standards:

  • SOC 2 Type II: Certified security controls
  • GDPR compliant: Data protection and user privacy
  • HIPAA ready: Additional security for healthcare data
  • PCI DSS: Secure handling of sensitive data

Track the health of your users’ connections and tokens:

Monitor key metrics for connected accounts:

# Get token health metrics for monitoring
account = actions.get_connected_account(
identifier="user_123",
connection_name="gmail"
)
# Key metrics to track:
print(f"Status: {account.status}")
print(f"Created: {account.created_at}")
print(f"Last updated: {account.updated_at}")
print(f"Scopes: {account.scopes}")
# Calculate time until re-authentication may be needed
# (if using providers with expiring refresh tokens)

Implement monitoring to catch issues early:

  1. Regular status checks - Poll connected account status daily
  2. Error rate tracking - Monitor tool execution failures
  3. Refresh failure alerts - Alert on repeated refresh failures
  4. User notifications - Notify users proactively when re-auth needed
  5. Dashboard visibility - Show connection status in your app
  • Trust automatic refresh: Let Scalekit handle token refresh automatically
  • Check status first: Verify account status before critical operations
  • Handle failures gracefully: Implement proper error handling for expired tokens
  • Notify users proactively: Alert users before connections become inactive
  • Clear status indicators: Show users their connection status
  • Easy re-authentication: Provide simple re-auth flows
  • Graceful degradation: Handle expired tokens without breaking your app
  • Helpful error messages: Explain what users need to do
  • Never expose tokens: Never send tokens to client applications
  • Minimize token access: Limit who can access token data
  • Regular audits: Review token access logs regularly
  • Rotate credentials: Regularly rotate OAuth client credentials
  • Cache account status: Cache status checks appropriately (1-5 minutes)
  • Batch operations: Group multiple tool executions when possible
  • Async refresh: Don’t block user operations on token refresh
  • Monitor latency: Track token refresh times and failures

Issue: Account status shows EXPIRED

  • Cause: Access token expired and refresh failed
  • Solution: Check refresh token validity, may need user re-authentication

Issue: Tool execution fails with authentication error

  • Cause: Token invalid or revoked by user
  • Solution: Generate new authorization link for user

Issue: Frequent refresh failures

  • Cause: Provider API issues or invalid credentials
  • Solution: Check provider status, verify OAuth credentials

Issue: User reports connection not working

  • Cause: Refresh token expired (for providers with expiring refresh tokens)
  • Solution: User must re-authenticate via new authorization link
  1. Check account status - Verify connected account status
  2. Review error messages - Examine detailed error responses
  3. Check provider status - Verify third-party provider is operational
  4. Test manual refresh - Try manually refreshing tokens
  5. Verify credentials - Ensure OAuth credentials are correct
  6. Check scopes - Verify required scopes are granted
  7. Review audit logs - Check Scalekit dashboard for token events

Now that you understand token management, learn about: