Skip to main content
Version: 1.0.0

Authentication

TwinEdge API supports multiple authentication methods to secure access to your industrial data.

Authentication Methods

MethodUse CaseSecurity Level
API KeysServer-to-server, automationHigh
OAuth 2.0User applicationsHigh
Session TokensWeb dashboardMedium

API Keys

API keys are the recommended method for server-to-server communication and automation.

Creating an API Key

  1. Go to SettingsAPI Keys
  2. Click Create API Key
  3. Configure:
    • Name: Descriptive identifier
    • Permissions: Select allowed scopes
    • Expiration: Optional expiry date
  4. Click Create
  5. 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

ScopeDescription
read:assetsRead asset data
write:assetsCreate/update assets
read:telemetryRead sensor data
write:telemetryIngest telemetry
read:alertsView alerts
write:alertsCreate/manage alerts
adminFull access

Key Rotation

Rotate keys regularly for security:

  1. Create a new API key
  2. Update your applications
  3. Delete the old key

Revoking Keys

Revoke compromised or unused keys:

  1. Go to SettingsAPI Keys
  2. Find the key to revoke
  3. Click Revoke
  4. Confirm deletion

OAuth 2.0

OAuth 2.0 is used for user-facing applications that need to act on behalf of users.

Supported Flows

FlowUse Case
Authorization CodeWeb applications
Authorization Code + PKCEMobile/SPA applications
Client CredentialsService 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

  1. Go to SettingsOAuth Applications
  2. Click Register Application
  3. Provide:
    • Name: Application name
    • Redirect URIs: Callback URLs
    • Application Type: Web, Mobile, SPA
  4. Receive Client ID and Secret

JWT Tokens

Token Structure

TwinEdge uses JWTs (JSON Web Tokens):

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c2VyLTEyMyIsIm9yZyI6Im9yZy00NTYiLC...}.
signature

Token Claims

ClaimDescription
subUser ID
orgOrganization ID
scopeGranted permissions
expExpiration timestamp
iatIssued 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

  1. Never commit keys to version control

    # .gitignore
    .env
    *.key
  2. Use environment variables

    import os
    api_key = os.environ.get('TWINEDGE_API_KEY')
  3. Restrict key scope

    • Only grant necessary permissions
    • Use read-only keys when possible
  4. Set expiration dates

    • Rotate keys every 90 days
    • Revoke unused keys
  5. Monitor key usage

    • Review API logs regularly
    • Set up alerts for unusual activity

Token Security

  1. Store securely

    • Use secure storage (Keychain, Credential Manager)
    • Never store in localStorage for sensitive apps
  2. Use HTTPS only

    • All API calls over HTTPS
    • Verify SSL certificates
  3. Implement token refresh

    • Don't use long-lived tokens
    • Refresh before expiration
  4. 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"
}
ErrorHTTP StatusDescription
invalid_token401Token invalid or expired
insufficient_scope403Missing required permissions
invalid_client401Unknown client ID
invalid_grant400Invalid 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