Token lifecycle & session management

View as Markdown

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:

TokenPurposeExpiry
Access tokenUsed to authenticate API requests7 days
Refresh tokenUsed to generate new access tokens30 days

Authentication flow

The token lifecycle typically follows this flow:

API key → login → access token + refresh token
use access token for requests
access token expires
use refresh token to get new access token

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:

Authorization: Bearer <access_token>

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:

  1. Detect authentication error
  2. Trigger token refresh

Step 4: Refresh token

Use the refresh token to generate a new access token.

refresh_token → new access_token

Replace the expired token with the new one.


Store and manage tokens on your backend.

Flow:

user request
backend checks token validity
if expired → refresh token
call AISquare API

Why this works best:

  • Keeps tokens secure
  • Avoids exposing credentials
  • Centralizes token management

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:

if current_time > expiry_time - buffer:
refresh token

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

user_id → access_token + refresh_token

Rotate tokens safely

  • Always replace old tokens after refresh
  • Avoid using stale tokens

When to use API key vs tokens

ScenarioRecommended
Simple backend callsAPI key
User sessionsAccess + refresh tokens
Long-running appsTokens with refresh

Putting it all together

  1. Register user → get API key
  2. Login → get tokens
  3. Use access token for requests
  4. Refresh when expired
  5. Repeat