Token lifecycle & session management
This guide explains how authentication tokens work in AISquare and how to manage them reliably in production systems.
Overview
AISquare supports a token-based authentication flow built on:
- Access tokens
- Refresh tokens
These tokens allow you to securely authenticate users without repeatedly sending API keys.
Token types
AISquare provides two types of tokens:
Authentication flow
The token lifecycle typically follows this flow:
Step 1: Obtain tokens
Use the login endpoint with the user’s API key.
Result:
- Access token
- Refresh token
Step 2: Use access token
Include the access token in API requests:
This token is used for all authenticated requests.
Step 3: Handle expiration
Access tokens expire after 7 days.
When a request fails due to expiration:
- Detect authentication error
- Trigger token refresh
Step 4: Refresh token
Use the refresh token to generate a new access token.
Replace the expired token with the new one.
Recommended implementation
Backend-managed tokens (recommended)
Store and manage tokens on your backend.
Flow:
Why this works best:
- Keeps tokens secure
- Avoids exposing credentials
- Centralizes token management
Frontend-managed tokens (not recommended)
Avoid storing tokens in frontend apps.
Risks:
- Token leakage
- Security vulnerabilities
- Difficult refresh handling
Token refresh strategies
1. Reactive refresh (simple)
- Attempt API request
- If it fails due to expiry → refresh token
2. Proactive refresh (better)
- Track token expiry time
- Refresh before expiration
Example:
3. Background refresh (advanced)
- Refresh tokens periodically
- Ensure uninterrupted sessions
Handling failures
Expired access token
- Response returns authentication error
- Trigger refresh flow
Expired refresh token
- User must re-authenticate
- Generate new tokens using API key
Invalid token
- Clear stored tokens
- Restart authentication flow
Token storage best practices
Store securely
- Use encrypted storage
- Avoid plain text storage
Associate with user
Rotate tokens safely
- Always replace old tokens after refresh
- Avoid using stale tokens
When to use API key vs tokens
Putting it all together
- Register user → get API key
- Login → get tokens
- Use access token for requests
- Refresh when expired
- Repeat
Related pages
- Authentication — all supported auth methods
- User onboarding & account lifecycle — register users and get API keys
- Integration patterns — architecture guidance
- Errors — handling 401 and token expiry errors

