Authentication
Learn how to authenticate with the AquaCloud Integration API using Keycloak-based security.
Overview
The AquaCloud Integration API uses industry-standard OAuth 2.0 / OpenID Connect authentication through Keycloak. All API requests require a valid access token.
Authentication Flow
Obtaining Access Tokens
Username/Password Authentication
The simplest way to authenticate for development and testing:
curl -X POST "https://api.aquacloud.ai/v3/auth/token" \
-H "Content-Type: application/json" \
-d '{
"username": "your-username",
"password": "your-password"
}'
Response:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh_token": "def50200a1b2c3d4e5f6...",
"token_type": "bearer",
"expires_in": 3600,
"scope": "read write"
}
Client Credentials Flow
For server-to-server authentication (recommended for production):
curl -X POST "https://api.aquacloud.ai/v3/auth/token" \
-H "Content-Type: application/json" \
-d '{
"grant_type": "client_credentials",
"client_id": "your-client-id",
"client_secret": "your-client-secret"
}'
Using Access Tokens
Include the access token in the Authorization header of all API requests:
curl -X GET "https://api.aquacloud.ai/v3/database/tables" \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
Token Management
Token Expiration
Access tokens expire after 1 hour (3600 seconds). Monitor the expires_in field in the authentication response.
Refresh Tokens
Use refresh tokens to obtain new access tokens without re-authenticating:
curl -X POST "https://api.aquacloud.ai/v3/auth/refresh" \
-H "Content-Type: application/json" \
-d '{
"refresh_token": "def50200a1b2c3d4e5f6..."
}'
Response:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh_token": "def50200a1b2c3d4e5f6...",
"token_type": "bearer",
"expires_in": 3600
}
Token Validation
Validate a token and get user information:
curl -X GET "https://api.aquacloud.ai/v3/auth/userinfo" \
-H "Authorization: Bearer your-access-token"
Response:
{
"sub": "user-123",
"username": "john.doe",
"email": "john.doe@aquafarm.com",
"roles": ["farmer", "analyst"],
"farmer_id": "farm_001",
"permissions": [
"read:own_farm_data",
"write:reports"
]
}
Role-Based Access Control
The API implements role-based access control (RBAC) with the following roles:
Roles
| Role | Description | Permissions |
|---|---|---|
admin | System administrators | Full access to all data and endpoints |
analyst | Data analysts | Read access to aggregated data across farms |
farmer | Individual farm operators | Read/write access to own farm data only |
readonly | Limited access users | Read-only access to assigned data |
Data Filtering
Access control is automatically applied based on user roles:
- Farmers: Can only access data for their assigned
farmer_id - Analysts: Can access aggregated data but not raw sensitive information
- Admins: Have unrestricted access
Example of automatic filtering for farmers:
-- User query
SELECT * FROM fish_growth_data WHERE measurement_date >= '2024-01-01'
-- Automatically modified to
SELECT * FROM fish_growth_data
WHERE measurement_date >= '2024-01-01'
AND farmer_id = 'farm_001' -- Added automatically
API Keys (Alternative)
For simplified authentication in development environments, API keys are supported:
Creating API Keys
API keys can be generated through the AquaCloud dashboard or by contacting support.
Using API Keys
curl -X GET "https://api.aquacloud.ai/v3/database/tables" \
-H "X-API-Key: aqc_1234567890abcdef..."
API keys provide limited functionality compared to OAuth tokens and should only be used for development or read-only access.
Best Practices
Token Storage
- Never store tokens in client-side code or version control
- Use secure storage mechanisms (environment variables, secure vaults)
- Implement proper token rotation in production applications
Error Handling
Handle authentication errors gracefully:
import requests
def make_authenticated_request(url, token, max_retries=3):
headers = {"Authorization": f"Bearer {token}"}
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code == 401:
# Token expired, refresh it
token = refresh_token()
headers["Authorization"] = f"Bearer {token}"
continue
elif response.status_code == 403:
# Permission denied
raise PermissionError("Access denied to resource")
return response.json()
raise Exception("Max retries exceeded")
Token Refresh Strategy
Implement proactive token refresh:
import time
import jwt
def should_refresh_token(token, buffer_seconds=300):
"""Check if token should be refreshed (5 min buffer)"""
try:
decoded = jwt.decode(token, options={"verify_signature": False})
exp_time = decoded.get('exp', 0)
return time.time() + buffer_seconds >= exp_time
except:
return True # If we can't decode, assume it needs refresh
Environment Configuration
Development
# .env file
AQUACLOUD_API_URL=https://api.aquacloud.ai
AQUACLOUD_USERNAME=your-dev-username
AQUACLOUD_PASSWORD=your-dev-password
Production
# .env file
AQUACLOUD_API_URL=https://api.aquacloud.ai
AQUACLOUD_CLIENT_ID=your-production-client-id
AQUACLOUD_CLIENT_SECRET=your-production-client-secret
AQUACLOUD_GRANT_TYPE=client_credentials
Common Authentication Errors
401 Unauthorized
{
"error": "unauthorized",
"message": "Access token expired",
"code": 401
}
Solutions:
- Refresh your access token
- Re-authenticate if refresh token is also expired
- Verify token format and encoding
403 Forbidden
{
"error": "forbidden",
"message": "Insufficient permissions for this resource",
"code": 403
}
Solutions:
- Check user roles and permissions
- Contact admin to request additional access
- Verify you're accessing the correct farm data
429 Rate Limited
{
"error": "rate_limit_exceeded",
"message": "Too many authentication requests",
"code": 429,
"retry_after": 60
}
Solutions:
- Implement exponential backoff
- Cache tokens longer to reduce authentication frequency
- Consider using refresh tokens instead of re-authenticating
Security Considerations
Transport Security
- All API communications use HTTPS/TLS 1.2+
- Certificate pinning recommended for mobile applications
Token Security
- Access tokens are short-lived (1 hour) to limit exposure
- Refresh tokens are long-lived but can be revoked
- All tokens use strong cryptographic signatures
Audit Logging
- All authentication events are logged
- Failed authentication attempts trigger security alerts
- Access patterns are monitored for anomalies
Getting Credentials
To get started with the AquaCloud Integration API:
- Existing Customers: Contact your account manager
- New Users: Request access
- Developers: Use the developer portal
Need help with authentication? Contact support.