Authentication
TwinEdge API supports multiple authentication methods to secure access to your industrial data.
Authentication Methods
| Method | Use Case | Security Level |
|---|---|---|
| API Keys | Server-to-server, automation | High |
| OAuth 2.0 | User applications | High |
| Session Tokens | Web dashboard | Medium |
API Keys
API keys are the recommended method for server-to-server communication and automation.
Creating an API Key
- Go to Settings → API Keys
- Click Create API Key
- Configure:
- Name: Descriptive identifier
- Permissions: Select allowed scopes
- Expiration: Optional expiry date
- Click Create
- Copy the key immediately - it won't be shown again
Using API Keys
Include the API key in the Authorization header:
curl -X GET "https://api.twinedgeai.com/v1/assets" \
-H "Authorization: Bearer YOUR_API_KEY"
Or in programming languages:
Python:
import requests
headers = {
"Authorization": "Bearer YOUR_API_KEY"
}
response = requests.get(
"https://api.twinedgeai.com/v1/assets",
headers=headers
)
JavaScript:
const response = await fetch('https://api.twinedgeai.com/v1/assets', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
API Key Scopes
| Scope | Description |
|---|---|
read:assets | Read asset data |
write:assets | Create/update assets |
read:telemetry | Read sensor data |
write:telemetry | Ingest telemetry |
read:alerts | View alerts |
write:alerts | Create/manage alerts |
admin | Full access |
Key Rotation
Rotate keys regularly for security:
- Create a new API key
- Update your applications
- Delete the old key
Revoking Keys
Revoke compromised or unused keys:
- Go to Settings → API Keys
- Find the key to revoke
- Click Revoke
- Confirm deletion
OAuth 2.0
OAuth 2.0 is used for user-facing applications that need to act on behalf of users.
Supported Flows
| Flow | Use Case |
|---|---|
| Authorization Code | Web applications |
| Authorization Code + PKCE | Mobile/SPA applications |
| Client Credentials | Service accounts |
Authorization Code Flow
Step 1: Redirect to Authorization
GET https://auth.twinedgeai.com/oauth/authorize?
client_id=YOUR_CLIENT_ID&
redirect_uri=https://yourapp.com/callback&
response_type=code&
scope=read:assets read:telemetry&
state=RANDOM_STATE
Step 2: Handle Callback
User is redirected back with authorization code:
https://yourapp.com/callback?code=AUTH_CODE&state=RANDOM_STATE
Step 3: Exchange Code for Tokens
POST https://auth.twinedgeai.com/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=AUTH_CODE&
redirect_uri=https://yourapp.com/callback&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4..."
}
Authorization Code + PKCE
For mobile and single-page applications where client secrets can't be safely stored.
Step 1: Generate Code Verifier and Challenge
// Generate random code verifier
const codeVerifier = generateRandomString(64);
// Create SHA-256 hash and base64url encode
const codeChallenge = base64url(sha256(codeVerifier));
Step 2: Authorization Request
GET https://auth.twinedgeai.com/oauth/authorize?
client_id=YOUR_CLIENT_ID&
redirect_uri=https://yourapp.com/callback&
response_type=code&
scope=read:assets&
state=RANDOM_STATE&
code_challenge=CODE_CHALLENGE&
code_challenge_method=S256
Step 3: Token Exchange
POST https://auth.twinedgeai.com/oauth/token
grant_type=authorization_code&
code=AUTH_CODE&
redirect_uri=https://yourapp.com/callback&
client_id=YOUR_CLIENT_ID&
code_verifier=CODE_VERIFIER
Client Credentials Flow
For service-to-service authentication without user context.
POST https://auth.twinedgeai.com/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET&
scope=read:telemetry
Refreshing Tokens
Access tokens expire after 1 hour. Use the refresh token to get new tokens:
POST https://auth.twinedgeai.com/oauth/token
grant_type=refresh_token&
refresh_token=YOUR_REFRESH_TOKEN&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET
Registering OAuth Applications
- Go to Settings → OAuth Applications
- Click Register Application
- Provide:
- Name: Application name
- Redirect URIs: Callback URLs
- Application Type: Web, Mobile, SPA
- Receive Client ID and Secret
JWT Tokens
Token Structure
TwinEdge uses JWTs (JSON Web Tokens):
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c2VyLTEyMyIsIm9yZyI6Im9yZy00NTYiLC...}.
signature
Token Claims
| Claim | Description |
|---|---|
sub | User ID |
org | Organization ID |
scope | Granted permissions |
exp | Expiration timestamp |
iat | Issued at timestamp |
Validating Tokens
Validate tokens using TwinEdge's public keys:
GET https://auth.twinedgeai.com/.well-known/jwks.json
import jwt
from jwt import PyJWKClient
jwks_client = PyJWKClient("https://auth.twinedgeai.com/.well-known/jwks.json")
signing_key = jwks_client.get_signing_key_from_jwt(token)
decoded = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience="https://api.twinedgeai.com"
)
Security Best Practices
API Key Security
-
Never commit keys to version control
# .gitignore
.env
*.key -
Use environment variables
import os
api_key = os.environ.get('TWINEDGE_API_KEY') -
Restrict key scope
- Only grant necessary permissions
- Use read-only keys when possible
-
Set expiration dates
- Rotate keys every 90 days
- Revoke unused keys
-
Monitor key usage
- Review API logs regularly
- Set up alerts for unusual activity
Token Security
-
Store securely
- Use secure storage (Keychain, Credential Manager)
- Never store in localStorage for sensitive apps
-
Use HTTPS only
- All API calls over HTTPS
- Verify SSL certificates
-
Implement token refresh
- Don't use long-lived tokens
- Refresh before expiration
-
Handle token revocation
- Clear tokens on logout
- Handle 401 responses gracefully
Error Responses
Authentication Errors
{
"error": "invalid_token",
"error_description": "The access token is invalid or expired"
}
| Error | HTTP Status | Description |
|---|---|---|
invalid_token | 401 | Token invalid or expired |
insufficient_scope | 403 | Missing required permissions |
invalid_client | 401 | Unknown client ID |
invalid_grant | 400 | Invalid authorization code |
Handling 401 Errors
response = requests.get(url, headers=headers)
if response.status_code == 401:
# Token expired, refresh it
new_token = refresh_access_token()
headers['Authorization'] = f'Bearer {new_token}'
response = requests.get(url, headers=headers)
SDK Authentication
Python SDK
from twinedge import TwinEdgeClient
# API Key authentication
client = TwinEdgeClient(api_key="YOUR_API_KEY")
# OAuth authentication
client = TwinEdgeClient(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET"
)
JavaScript SDK
import { TwinEdgeClient } from '@twinedge/sdk';
// API Key authentication
const client = new TwinEdgeClient({
apiKey: 'YOUR_API_KEY'
});
// OAuth authentication
const client = new TwinEdgeClient({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
Next Steps
- REST Endpoints - Available API endpoints
- WebSocket API - Real-time data streaming
- Rate Limits - API usage limits