Authentication & API Keys
The Alaikis BI API uses two authentication methods: OAuth2 with JWT tokens for web users, and API Keys for machine-to-machine communication.
Authentication Methods
| Method | Use Case | Endpoints |
|---|---|---|
| OAuth2 JWT | Web applications, user sessions | /auth/*, /api/users/* |
| API Key | Server-to-server, SDK integration | All /api/* endpoints |
OAuth2 Authentication Flow
The API uses Casdoor as the OAuth2 identity provider for user authentication.
Authentication Flow
┌──────────┐ ┌──────────┐ ┌──────────┐
│ User's │ │ Alaikis │ │ Casdoor │
│ Browser │─────────▶│ API │─────────▶│ IDP │
└──────────┘ └──────────┘ └──────────┘
│ │ │
│ 1. Click Login │ │
│─────────────────────▶│ │
│ │ 2. Redirect to Casdoor
│ │─────────────────────▶│
│ 3. Login at Casdoor │ │
│◀────────────────────────────────────────────│
│ 4. OAuth Code │ │
│─────────────────────▶│ │
│ │ 5. Code → Token │
│ │─────────────────────▶│
│ │ 6. JWT + User Info │
│◀─────────────────────│ │
│ │ │
│ 7. Use JWT in Headers│ │
│─────────────────────▶│ │GET /auth/login
Initiates the OAuth2 login flow by redirecting to Casdoor's authorization page.
Response:
- HTTP 302 Redirect to Casdoor login page
GET /auth/callback
OAuth2 callback endpoint that receives the authorization code from Casdoor.
Query Parameters:
| Parameter | Type | Description |
|---|---|---|
| code | string | OAuth2 authorization code |
| state | string | State parameter for CSRF protection |
Process:
- Exchanges code for access token with Casdoor
- Retrieves user information
- Creates/updates user record in local database
- Issues JWT token for API access
- Redirects back to frontend with token
Redirect to Frontend:
https://your-app.com/auth/callback?token=jwt-token&user_id=123&username=johndoe&email=john@example.comUser Synchronization:
- New users are automatically created on first login
- Existing users have their information updated (name, email)
casdoor_idis stored as the unique user identifier
POST /auth/logout
Logs out the current user by constructing the Casdoor logout URL.
Response:
{
"logout_url": "https://casdoor.example.com/logout?redirect_uri=https://api.alaikis.com"
}Frontend should:
- Clear JWT token from local storage
- Redirect user to the logout URL
API Key Authentication
API keys are used for server-to-server communication and SDK integration.
Creating API Keys
API keys are created through the /api/tokens endpoints (see Token Management).
Request Format:
Authorization: Bearer your-api-keyKey Format:
alaikis_sk_<random-string>Security Note
API keys grant full access to your account. Never expose them in client-side code, public repositories, or browser environments.
Key Validation
The API validates API keys by:
- Checking the token exists in the database
- Verifying the token is active
- Retrieving the associated user record
- Checking user is active
Token Management
POST /api/tokens
Create a new API key.
Request Body:
{
"name": "Production Server Key",
"description": "For order processing integration",
"scopes": ["packing:read", "packing:write", "product-trace:*"]
}Parameters:
| Parameter | Type | Description |
|---|---|---|
| name | string | Human-readable name for the key |
| description | string | Optional description |
| scopes | string[] | Permission scopes (optional) |
Response:
{
"id": 1,
"token": "alaikis_sk_a1b2c3d4e5f6...",
"name": "Production Server Key",
"user_id": 123,
"created_at": "2024-01-15T10:30:00Z",
"is_active": true
}Key Display
The token value is only shown once at creation. Store it securely.
GET /api/tokens
List all API keys for the authenticated user.
Response:
{
"data": [
{
"id": 1,
"name": "Production Server Key",
"masked_token": "alaikis_sk_********...",
"created_at": "2024-01-15T10:30:00Z",
"last_used": "2024-01-20T15:45:00Z",
"is_active": true
}
],
"total": 1
}GET /api/tokens/[id]
Get details for a specific API key by ID.
Response:
{
"id": 1,
"name": "Production Server Key",
"description": "For order processing integration",
"masked_token": "alaikis_sk_********...",
"scopes": ["packing:read", "packing:write"],
"created_at": "2024-01-15T10:30:00Z",
"last_used": "2024-01-20T15:45:00Z",
"is_active": true
}DELETE /api/tokens/[id]
Revoke (deactivate) an API key by ID.
Response:
{
"success": true,
"message": "API key revoked successfully"
}Immediate Effect
Revoked keys are invalid immediately. Ongoing requests may complete, but new requests will fail.
User Management
GET /api/users/me
Get current user profile.
Response:
{
"id": 123,
"username": "johndoe",
"email": "john@example.com",
"full_name": "John Doe",
"casdoor_id": "user-123-abc",
"is_active": true,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}GET /api/users/[id]
Get user by ID (admin only).
PUT /api/users/[id]
Update user information (admin only or self).
Request Body:
{
"full_name": "John Smith Doe",
"email": "john.smith@example.com"
}DELETE /api/users/[id]
Deactivate user account (admin only).
JWT Token Details
Token Structure
JWT tokens contain the following claims:
{
"sub": "casdoor-user-id-123",
"iat": 1705305600,
"exp": 1705392000,
"iss": "alaikis-api",
"aud": "alaikis-frontend"
}Token Expiration
| Token Type | Duration |
|---|---|
| Access Token | 24 hours |
| Refresh Token | 7 days |
Verifying Tokens
Tokens are signed using HS256 (HMAC SHA256) with the secret key from environment variables.
Verification Steps:
- Check signature validity
- Verify issuer (
iss) matches expected value - Check token is not expired (
exp) - Extract
subclaim (casdoor user ID) - Look up user in database by casdoor_id
Security Best Practices
1. Secure Key Storage
Good:
# Environment variable
import os
API_KEY = os.getenv("ALAIKIS_API_KEY")
# Secrets manager
from aws_secretsmanager import get_secret
API_KEY = get_secret("alaikis/api-key")Bad:
# Hardcoded - NEVER DO THIS
API_KEY = "alaikis_sk_12345..." # ❌ Security risk
# In client-side code
const apiKey = "alaikis_sk_12345..." // ❌ Exposed to users2. Key Rotation
Rotate API keys periodically:
# Create new key
POST /api/tokens
# Deploy new key to production
# Revoke old key
DELETE /api/tokens/{old_id}Recommended rotation interval: 90 days.
3. Least Privilege
Use scopes to limit key permissions:
{
"name": "Reports Service Key",
"scopes": [
"packing:read",
"product-trace:read"
// No write permissions
]
}4. Audit Usage
Monitor API key usage:
- Track
last_usedtimestamp - Review access logs
- Set up alerts for unusual activity
Error Responses
Invalid Credentials
{
"detail": "Invalid authentication credentials"
}Status: 401 Unauthorized
Expired Token
{
"detail": "Token has expired"
}Status: 401 Unauthorized
Revoked Key
{
"detail": "API key has been revoked"
}Status: 401 Unauthorized
Missing Authorization
{
"detail": "Authorization header required"
}Status: 401 Unauthorized
SDK Authentication Examples
Python SDK
from alibi.client import AlaikisClient
# With API Key
client = AlaikisClient(api_key="alaikis_sk_...")
# With JWT Token
client = AlaikisClient(jwt_token="eyJhbGciOiJIUzI1NiIs...")JavaScript SDK
import { AlaikisClient } from '@alaikis/sdk';
const client = new AlaikisClient({
apiKey: 'alaikis_sk_...'
// OR
jwtToken: 'eyJhbGciOiJIUzI1NiIs...'
});cURL
# API Key
curl -H "Authorization: Bearer alai kis_sk_..." \
https://api.alaikis.com/api/users/me
# JWT Token
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
https://api.alaikis.com/api/users/meEnvironment Variables
Authentication configuration:
# Casdoor
CASDOOR_ENDPOINT=https://casdoor.example.com
CASDOOR_CLIENT_ID=your-client-id
CASDOOR_CLIENT_SECRET=your-client-secret
CASDOOR_ORGANIZATION_NAME=alaikis
CASDOOR_APPLICATION_NAME=bi-api
# JWT
JWT_SECRET_KEY=your-jwt-secret
JWT_ALGORITHM=HS256
# Frontend
FRONTEND_URL=https://your-app.com