Authentication

aiOla uses a secure two-tier authentication system that combines API keys with JWT access tokens. This approach provides both security and flexibility, allowing you to keep sensitive credentials on the backend while enabling frontend applications to make authenticated requests.

How Authentication Works

Overview

aiOla’s authentication flow follows this pattern:

  1. API Key Exchange: Your backend application uses an API key to request an access token
  2. Token Generation: aiOla’s authentication service returns a JWT access token
  3. API Requests: Your application uses the access token to make authenticated requests to aiOla services

Why This Architecture?

This two-tier system provides several key benefits:

🔐 Enhanced Security

  • API Key Protection: Your sensitive API key never leaves your backend
  • Token Rotation: Access tokens have limited lifespans and can be rotated regularly
  • Principle of Least Privilege: Frontend applications only receive temporary access tokens

🏗️ Architectural Flexibility

  • Frontend Freedom: Client applications can authenticate without exposing secrets
  • Scalable Design: Generate tokens for multiple clients from a single API key
  • Environment Separation: Different tokens for development, staging, and production

🛡️ Risk Mitigation

  • Limited Exposure: If a token is compromised, it expires automatically
  • Centralized Control: Revoke access by rotating the API key on your backend
  • Audit Trail: Track token generation and usage patterns

Implementation Guide

Backend: Token Generation

Your backend is responsible for exchanging API keys for access tokens:

Python
1import os
2from aiola import AiolaClient
3
4# Generate an access token using your API key
5def get_access_token():
6 try:
7 result = AiolaClient.grant_token(
8 api_key=os.getenv("AIOLA_API_KEY")
9 )
10 return {
11 "access_token": result['accessToken'],
12 "session_id": result['sessionId'],
13 }
14 except Exception as e:
15 print(f"Token generation failed: {e}")
16 return None
17
18# Create client with access token
19def create_client(access_token):
20 return AiolaClient(access_token=access_token)

Frontend: Using Access Tokens

Once you have an access token, use it in the Authorization header:

1import { AiolaClient } from '@aiola/sdk';
2
3// Generate access token (typically done on backend)
4const getAccessToken = async () => {
5 try {
6 const { accessToken, sessionId } = await AiolaClient.grantToken({
7 apiKey: process.env.AIOLA_API_KEY
8 });
9 return { accessToken, sessionId };
10 } catch (error) {
11 console.error('Token generation failed:', error);
12 throw error;
13 }
14};
15
16// Create client and use for requests
17const makeAiolaRequest = async (audioData) => {
18 const { accessToken } = await getAccessToken();
19
20 const client = new AiolaClient({ accessToken });
21
22 const transcript = await client.stt.transcribeFile({
23 file: audioData,
24 language: 'en'
25 });
26
27 return transcript;
28};

Security Best Practices

API Key Management

Never expose your API key in frontend code or version control

Do:

  • Store API keys in environment variables
  • Use secure secret management systems in production
  • Rotate API keys regularly
  • Limit API key access to necessary backend services only

Don’t:

  • Include API keys in frontend applications
  • Commit API keys to version control
  • Share API keys across environments
  • Store API keys in plain text files

Token Handling

Backend Token Management

1import os
2from datetime import datetime, timedelta
3import redis
4
5# Example token caching to avoid unnecessary API calls
6redis_client = redis.Redis(host='localhost', port=6379)
7
8def get_cached_token():
9 cached_token = redis_client.get('aiola_access_token')
10 if cached_token:
11 return cached_token.decode('utf-8')
12
13 # Generate new token
14 token_data = client.grant_token()
15
16 # Cache token with expiration buffer (5 minutes before actual expiry)
17 cache_duration = token_data.expires_in - 300
18 redis_client.setex('aiola_access_token', cache_duration, token_data.access_token)
19
20 return token_data.access_token

Frontend Token Management

1class TokenManager {
2 constructor() {
3 this.token = null;
4 this.tokenExpiry = null;
5 }
6
7 async getValidToken() {
8 // Check if current token is still valid (with 5-minute buffer)
9 if (this.token && this.tokenExpiry > Date.now() + 300000) {
10 return this.token;
11 }
12
13 // Fetch new token from backend
14 const tokenData = await this.fetchTokenFromBackend();
15 this.token = tokenData.access_token;
16 this.tokenExpiry = Date.now() + (tokenData.expires_in * 1000);
17
18 return this.token;
19 }
20
21 async fetchTokenFromBackend() {
22 const response = await fetch('/api/auth/token');
23 if (!response.ok) {
24 throw new Error('Failed to fetch access token');
25 }
26 return response.json();
27 }
28}

Environment Configuration

Development Setup

$# .env file
>AIOLA_API_KEY=your-development-api-key
>AIOLA_ENDPOINT=https://api.aiola.com

Production Setup

For production deployments, consider:

Enterprise Endpoints

$# Custom enterprise endpoint
>AIOLA_ENDPOINT=https://your-company.aiola-enterprise.com
>AIOLA_API_KEY=your-production-api-key

Enterprise Configuration

1# Enterprise/custom endpoint configuration
2result = AiolaClient.grant_token(
3 api_key=os.getenv("AIOLA_API_KEY"),
4 auth_base_url="https://your-company.auth.aiola.ai"
5)
6
7client = AiolaClient(
8 access_token=result['accessToken'],
9 base_url="https://your-company.api.aiola.ai"
10)

Error Handling

Common Authentication Errors

401 Unauthorized

1{
2 "error": {
3 "code": "UNAUTHORIZED",
4 "message": "Invalid or expired access token"
5 }
6}

Solutions:

  • Verify token is included in Authorization header
  • Check token format: Bearer <token>
  • Generate a new access token

403 Forbidden

1{
2 "error": {
3 "code": "FORBIDDEN",
4 "message": "API key does not have required permissions"
5 }
6}

Solutions:

  • Verify API key has correct permissions
  • Check if API key is active and not revoked
  • Contact support for permission adjustments

FAQ

Access tokens typically last 30 minutes. The SDK handles token management internally, but you should implement refresh logic for long-running applications.

Yes, access tokens can be shared across applications, but consider security implications. For better isolation, generate separate tokens for different services.

Immediately rotate your API key in the aiOla dashboard. All existing access tokens will become invalid, requiring new token generation.

Token lifetimes are fixed for security reasons. Implement automatic token refresh in your applications instead.

Yes, use separate API keys for development, staging, and production environments for better security and monitoring.

Next Steps


Need Help? If you encounter issues with authentication, contact our support team.