Skip to content

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

MethodUse CaseEndpoints
OAuth2 JWTWeb applications, user sessions/auth/*, /api/users/*
API KeyServer-to-server, SDK integrationAll /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:

ParameterTypeDescription
codestringOAuth2 authorization code
statestringState parameter for CSRF protection

Process:

  1. Exchanges code for access token with Casdoor
  2. Retrieves user information
  3. Creates/updates user record in local database
  4. Issues JWT token for API access
  5. 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.com

User Synchronization:

  • New users are automatically created on first login
  • Existing users have their information updated (name, email)
  • casdoor_id is stored as the unique user identifier

POST /auth/logout

Logs out the current user by constructing the Casdoor logout URL.

Response:

json
{
    "logout_url": "https://casdoor.example.com/logout?redirect_uri=https://api.alaikis.com"
}

Frontend should:

  1. Clear JWT token from local storage
  2. 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:

http
Authorization: Bearer your-api-key

Key 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:

  1. Checking the token exists in the database
  2. Verifying the token is active
  3. Retrieving the associated user record
  4. Checking user is active

Token Management

POST /api/tokens

Create a new API key.

Request Body:

json
{
    "name": "Production Server Key",
    "description": "For order processing integration",
    "scopes": ["packing:read", "packing:write", "product-trace:*"]
}

Parameters:

ParameterTypeDescription
namestringHuman-readable name for the key
descriptionstringOptional description
scopesstring[]Permission scopes (optional)

Response:

json
{
    "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:

json
{
    "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:

json
{
    "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:

json
{
    "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:

json
{
    "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:

json
{
    "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:

json
{
    "sub": "casdoor-user-id-123",
    "iat": 1705305600,
    "exp": 1705392000,
    "iss": "alaikis-api",
    "aud": "alaikis-frontend"
}

Token Expiration

Token TypeDuration
Access Token24 hours
Refresh Token7 days

Verifying Tokens

Tokens are signed using HS256 (HMAC SHA256) with the secret key from environment variables.

Verification Steps:

  1. Check signature validity
  2. Verify issuer (iss) matches expected value
  3. Check token is not expired (exp)
  4. Extract sub claim (casdoor user ID)
  5. Look up user in database by casdoor_id

Security Best Practices

1. Secure Key Storage

Good:

python
# 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:

python
# Hardcoded - NEVER DO THIS
API_KEY = "alaikis_sk_12345..."  # ❌ Security risk

# In client-side code
const apiKey = "alaikis_sk_12345..." // ❌ Exposed to users

2. Key Rotation

Rotate API keys periodically:

bash
# 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:

json
{
    "name": "Reports Service Key",
    "scopes": [
        "packing:read",
        "product-trace:read"
        // No write permissions
    ]
}

4. Audit Usage

Monitor API key usage:

  • Track last_used timestamp
  • Review access logs
  • Set up alerts for unusual activity

Error Responses

Invalid Credentials

json
{
    "detail": "Invalid authentication credentials"
}

Status: 401 Unauthorized

Expired Token

json
{
    "detail": "Token has expired"
}

Status: 401 Unauthorized

Revoked Key

json
{
    "detail": "API key has been revoked"
}

Status: 401 Unauthorized

Missing Authorization

json
{
    "detail": "Authorization header required"
}

Status: 401 Unauthorized

SDK Authentication Examples

Python SDK

python
from alibi.client import AlaikisClient

# With API Key
client = AlaikisClient(api_key="alaikis_sk_...")

# With JWT Token
client = AlaikisClient(jwt_token="eyJhbGciOiJIUzI1NiIs...")

JavaScript SDK

javascript
import { AlaikisClient } from '@alaikis/sdk';

const client = new AlaikisClient({
    apiKey: 'alaikis_sk_...'
    // OR
    jwtToken: 'eyJhbGciOiJIUzI1NiIs...'
});

cURL

bash
# 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/me

Environment Variables

Authentication configuration:

bash
# 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