title: 'Authentication Guide' description: 'Complete guide to authenticating with the Lilith Wisdom Platform API' layout: 'guide' category: 'authentication' tags: ['auth', 'jwt', 'tokens', 'security']#
Overview#
The Lilith Wisdom Platform API uses JSON Web Tokens (JWT) for authentication. All API requests (except public endpoints) must include a valid JWT token in the Authorization header.
Authentication Methods#
We support multiple authentication methods depending on your use case:
- Client Credentials - For server-to-server communication
- Authorization Code - For web applications with user login
- API Keys - For simple integration scenarios
- Biometric Authentication - For mobile applications
Getting Started#
1. Create Developer Account#
First, create a developer account at https://portal.lilith.ai:
- Visit the developer portal
- Click "Sign Up"
- Complete the registration form
- Verify your email address
- Set up two-factor authentication
2. Generate API Credentials#
- Log in to your developer dashboard
- Navigate to API Keys → Create New Key
- Select the appropriate key type:
- Production: For live applications
- Staging: For testing and development
- Configure permissions and rate limits
- Copy your client ID and client secret
3. Choose Authentication Method#
Based on your application type, choose the appropriate authentication method:
- Web Applications: Authorization Code Flow
- Mobile Apps: Authorization Code Flow with PKCE
- Server-to-Server: Client Credentials Flow
- Simple Scripts: API Key Authentication
Client Credentials Flow#
Use this method for server-to-server communication where no user interaction is required.
Step 1: Request Access Token#
curl -X POST https://api.lilith.ai/v1/auth/token \
-H "Content-Type: application/json" \
-d '{
"grant_type": "client_credentials",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"scope": "api:read api:write"
}'
Step 2: Handle Response#
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "api:read api:write",
"refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
}
Step 3: Use Access Token#
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
https://api.lilith.ai/v1/users/me
Authorization Code Flow#
Use this method for web and mobile applications with user login.
Step 1: Redirect User to Authorization#
const authUrl =
`https://auth.lilith.ai/oauth/authorize?` +
`response_type=code&` +
`client_id=${encodeURIComponent(clientId)}&` +
`redirect_uri=${encodeURIComponent(redirectUri)}&` +
`scope=${encodeURIComponent('api:read api:write')}&` +
`state=${encodeURIComponent(generateState())}`;
window.location.href = authUrl;
Step 2: Handle Authorization Callback#
// In your callback handler
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
// Verify state to prevent CSRF
if (state !== storedState) {
throw new Error('Invalid state parameter');
}
// Exchange code for tokens
exchangeCodeForTokens(code);
Step 3: Exchange Code for Tokens#
curl -X POST https://auth.lilith.ai/oauth/token \
-H "Content-Type: application/json" \
-d '{
"grant_type": "authorization_code",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"code": "authorization_code_from_callback",
"redirect_uri": "https://your-app.com/callback",
"code_verifier": "code_verifier_from_pkce"
}'
API Key Authentication#
For simple integration scenarios, you can use API key authentication.
Using API Key in Header#
curl -H "X-API-Key: your_api_key" \
https://api.lilith.ai/v1/content/meditations
Using API Key as Query Parameter#
curl "https://api.lilith.ai/v1/content/meditations?api_key=your_api_key"
Token Management#
Token Storage#
Store tokens securely:
- Server-side: Use environment variables or secure key management
- Client-side: Use httpOnly cookies or secure storage
- Mobile: Use platform secure storage (Keychain, Keystore)
Token Refresh#
Access tokens expire after 1 hour. Use the refresh token to obtain a new token:
curl -X POST https://api.lilith.ai/v1/auth/refresh \
-H "Content-Type: application/json" \
-d '{
"grant_type": "refresh_token",
"refresh_token": "your_refresh_token",
"client_id": "your_client_id",
"client_secret": "your_client_secret"
}'
Token Revocation#
Revoke tokens when no longer needed:
curl -X POST https://api.lilith.ai/v1/auth/revoke \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-d '{
"token": "token_to_revoke",
"token_type_hint": "access_token"
}'
SDK Integration#
TypeScript/JavaScript#
import { LilithAPIClient } from '@lilith/sdk';
const client = new LilithAPIClient({
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
baseURL: 'https://api.lilith.ai',
});
// Client handles token management automatically
const user = await client.users.getCurrentUser();
Error Handling#
Common Authentication Errors#
| Error | Description | Solution |
|---|---|---|
invalid_client |
Invalid client credentials | Verify client ID and secret |
invalid_grant |
Invalid authorization code or refresh token | Request new authorization |
expired_token |
Access token has expired | Use refresh token to get new token |
insufficient_scope |
Token lacks required permissions | Request appropriate scopes |
Handling Token Expiration#
async function makeApiRequest(url: string, options: RequestOptions) {
try {
const response = await fetch(url, options);
if (response.status === 401) {
// Token expired, try to refresh
await refreshAccessToken();
// Retry request with new token
return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${getNewAccessToken()}`,
},
});
}
return response;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
Security Best Practices#
1. Protect Credentials#
- Never expose client secrets in client-side code
- Use environment variables for sensitive configuration
- Implement proper secrets management in production
2. Use HTTPS#
Always use HTTPS for API requests to prevent token interception:
// ✅ Good
const baseURL = 'https://api.lilith.ai';
// ❌ Bad
const baseURL = 'http://api.lilith.ai';
3. Validate Tokens#
Always validate JWT tokens before accepting them:
import jwt from 'jsonwebtoken';
function validateToken(token: string): boolean {
try {
const decoded = jwt.verify(token, publicKey);
return decoded.exp > Date.now() / 1000;
} catch (error) {
return false;
}
}
4. Implement Rate Limiting#
Respect rate limits and implement backoff strategies:
class RateLimitedClient {
private lastRequest = 0;
private minInterval = 100; // 100ms between requests
async makeRequest(url: string, options: RequestOptions) {
const now = Date.now();
const timeSinceLastRequest = now - this.lastRequest;
if (timeSinceLastRequest < this.minInterval) {
await new Promise((resolve) =>
setTimeout(resolve, this.minInterval - timeSinceLastRequest)
);
}
this.lastRequest = Date.now();
return fetch(url, options);
}
}
5. Scope Limitation#
Request only the permissions your application needs:
// ✅ Good - Specific scopes
const scopes = ['meditations:read', 'users:write'];
// ❌ Bad - Overly broad permissions
const scopes = ['api:*'];
Biometric Authentication#
For mobile applications, we support biometric authentication for enhanced
security. The React Native mobile app uses react-native-biometrics for
cross-platform biometric authentication on iOS and Android.
Testing Authentication#
Test Credentials#
Use the following test credentials for development:
- Client ID:
test_client_id - Client Secret:
test_client_secret - Test User:
test@example.com/password123
Mock Authentication#
For testing, you can mock the authentication flow:
class MockAuthService implements AuthService {
async authenticate(): Promise<AuthResult> {
return {
accessToken: 'mock_access_token',
refreshToken: 'mock_refresh_token',
expiresIn: 3600,
};
}
}
Troubleshooting#
Common Issues#
Q: I'm getting "invalid_client" errors A: Verify your client ID and secret are correct and haven't expired
Q: My refresh token isn't working A: Refresh tokens expire after 30 days. Request a new authorization
Q: CORS errors when making requests A: Ensure your redirect URI is registered in the developer portal
Q: Rate limit exceeded A: Implement proper backoff strategies and respect rate limits
Debug Mode#
Enable debug mode for additional logging:
const client = new LilithAPIClient({
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
debug: true, // Enables verbose logging
});
Support#
If you encounter authentication issues:
- Check the status page for service availability
- Review our API documentation
- Contact support at auth-support@lilith.ai
- Open an issue on GitHub
Next: Explore API Reference →