Skip to main content

Authentication

Upgrading to version 0.80.0

Version 0.80.0 removes /api/auth/permissions and /api/auth/kv-permissions; use /api/auth/keys/{id}/permissions.

Permission resources use a server-generated key id, or me for the caller's own key. A key's secret value is never a permission-resource identifier. Tokens issued before the upgrade receive a 401 and must be exchanged again through POST /api/auth/token.

SDK release. SDK version 0.32.0 supports these routes in every language: Rust (ekodb_client), Python (ekodb-client), TypeScript (@ekodb/ekodb-client), Kotlin (io.ekodb:ekodb-client-kt on Maven Central) and Go (github.com/ekoDB/ekodb-client-go v0.32.0). The new resources are the 0.80.0 contract. A server that serves them can report an older version while an upgrade is in progress, so integrations must detect the supported routes rather than relying only on the version string.

SDK admin clients expose this check as uses_key_permission_routes (Rust/Python), usesKeyPermissionRoutes (TypeScript/Kotlin), or UsesKeyPermissionRoutes (Go). They probe the authenticated GET /api/auth/keys/me/permissions route. Only 404 or 405 selects legacy routes; authentication, authorization, transport, and malformed-response errors do not trigger that fallback. The explicit legacy collection-permission edit requires detected legacy routes and a stable server version of at least 0.79.2. It is rejected on servers that serve the new routes.

Getting Your API Key​

After deploying your ekoDB instance, you'll need an API key to connect your application.

Step 1: Access Your Deployment​

  1. Go to app.ekodb.io
  2. Navigate to your deployment from the dashboard
  3. Click on the "Keys" tab

Direct link format: https://app.ekodb.io/deployments/{YOUR_DEPLOYMENT_ID}?active_tab=keys

Step 2: Use Your Admin API Key​

By default, ekoDB automatically generates an admin API key when you create a deployment. This key has full access to all collections and operations.

Admin Keys Are Sensitive

Admin API keys should only be used for development and testing. For production applications, create API keys with limited permissions (see below).

Step 3: Copy Your API Key​

Copy the API key from the dashboard and store it securely. You'll use this to initialize your client library.

Initialize Your Client

Once you have your API key, see the Client Libraries Installation Guide for complete code examples on how to configure your client in TypeScript, Rust, Python, Go, or Kotlin.

Client Libraries Handle Authentication

When using ekoDB client libraries (Rust, Python, TypeScript, Go, Kotlin), you don't need to manually manage JWT tokens. The client automatically handles token generation and renewal for you. Simply provide your API key when initializing the client.

Creating API Keys with Limited Permissions​

For production applications, create API keys with specific collection permissions.

Register API Key​

Register a new API key using the REST API. Pass the existing admin key in the api_key body field. The examples also send an admin token in the Authorization header. The api_key authenticates registration; the optional key field chooses the new key's secret.

Omit key to let the server generate a secret. If you supply key, version 0.80.0 requires at least 32 characters and at least 8 distinct characters. A value shaped like an id (32 lowercase hexadecimal characters) is rejected. Invalid keys return 400; a key already registered returns 409. The server generates id independently of the secret, and callers cannot choose it. Retain this id for permission changes and revocation. Registration uses action arrays such as ["read", "write"] for each collection. Permission resources return objects with boolean flags and optional field limits.

curl -X POST https://{EKODB_API_URL}/api/auth/register \
-H "Authorization: Bearer {ADMIN_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"api_key": "{ADMIN_KEY}",
"label": "{LABEL}",
"description": "{DESCRIPTION}",
"collection_permissions": {
"{COLLECTION_NAME}": ["read", "write"]
},
"is_admin": false
}'

Response:

{
"id": "0123456789abcdef0123456789abcdef",
"label": "{LABEL}",
"description": "{DESCRIPTION}",
"collection_permissions": {
"{COLLECTION_NAME}": { "read": true, "write": true }
},
"is_admin": false,
"key": "{YOUR_NEW_API_KEY}",
"kv_permissions": []
}

A key that is not an admin can also be registered with function_permissions, which maps a stored-function label, a label prefix ending in one *, or * to ["call"], for example "function_permissions": { "report_*": ["call"] }. A non-admin key registered without it can call no stored function. (In shadow mode the call is allowed and recorded as access_would_deny.) call is the only right. Set Function Permissions lists what a pattern may hold.

Using Your New API Key​

Once you have a scoped API key, use it to initialize your client:

use ekodb_client::Client;

let client = Client::builder()
.base_url("https://your-subdomain.production.google.ekodb.net")
.api_key("{YOUR_NEW_API_KEY}")
.build()?;

Generate JWT Token​

Generate a JWT token using your API key:

use ekodb_client::Client;

let client = Client::builder()
.base_url("https://your-subdomain.production.google.ekodb.net")
.api_key("YOUR_API_KEY")
.build()?;

// Client automatically handles JWT token generation
// No manual token generation needed when using the client library
Client Libraries Handle Token Management

When using ekoDB client libraries (Rust, Python, TypeScript, Go, Kotlin), you don't need to manually generate JWT tokens. The client automatically handles token generation, caching, and renewal. Only use direct API calls for token generation if you're not using a client library.

Use JWT Token​

Use the JWT token in the Authorization header:

use ekodb_client::Client;

let client = Client::builder()
.base_url("https://your-subdomain.production.google.ekodb.net")
.api_key("YOUR_API_KEY")
.build()?;

// Client automatically handles authentication
let collections = client.list_collections().await?;

println!("Collections: {:?}", collections);
Client Libraries Handle Authentication Automatically

When using ekoDB client libraries (Rust, Python, TypeScript, Go, Kotlin), you don't need to manually manage JWT tokens or set Authorization headers. Simply initialize the client with your API key, and all subsequent requests are automatically authenticated.

API Key Management​

List All API Keys​

Get a list of all API keys (admin only). Each entry includes its id and existing key metadata. Store the id separately from the secret value.

GET https://{EKODB_API_URL}/api/auth/keys
Authorization: Bearer {ADMIN_TOKEN}

# Response
[
{
"id": "0123456789abcdef0123456789abcdef",
"key": "{YOUR_NEW_API_KEY}",
"label": "Web App Key",
"description": "Scoped application access",
"is_admin": false,
"collection_permissions": {
"users": {
"read": true,
"write": true,
"select_fields": null,
"exclude_fields": null,
"writable_fields": null
}
},
"kv_permissions": []
}
]

Revoke API Key​

Permanently revoke an API key (admin only). Prefer the id from registration or the key listing so the secret stays out of the URL:

DELETE https://{EKODB_API_URL}/api/auth/keys/{key_id}
Authorization: Bearer {ADMIN_TOKEN}

# Response
{
"status": "success",
"message": "Key revoked successfully"
}

The revoke path also accepts the key's value, but that form is deprecated: the server answers it with a Deprecation: true header and a Warning header, and plans to refuse it in the next release. Revoke by id. The bootstrap admin key cannot be revoked, by id or by value; the request returns 403. Do not send a request body containing key; it returns 400.

Revocation is Permanent

Once revoked, an API key cannot be restored. Applications using the revoked key will immediately lose access.

Get User Permissions​

Read the caller's own key permissions with me, or with its server-generated id. Any valid token can read its own key's permissions. Reading another key requires an admin token. An unknown id, or a key value used instead of an id, returns 404. A token's sub identifies the key id.

GET https://{EKODB_API_URL}/api/auth/keys/me/permissions
Authorization: Bearer {YOUR_API_TOKEN}

# Response
{
"admin": false,
"collections": {
"users": {
"read": true,
"write": true,
"select_fields": ["name", "email"],
"exclude_fields": null,
"writable_fields": ["name"]
}
},
"kv": [
{ "prefix": "session:", "read": true, "write": true }
],
"functions": [
{ "pattern": "report_*" }
]
}

The same permission resource exposes these reads:

Suffix after /api/auth/keys/{key_id}/permissionsResult
/collectionsCollection entries, keyed by collection name
/collections/{name}One collection entry, or 404 if absent
/kvKV grants
/kv?prefix={prefix}KV grants filtered by prefix
/kv/{prefix}One KV grant
/functionsFunction call grants
/functions/{pattern}One function call grant, or 404 if absent

Set Collection Permissions​

Every permission change requires an admin token, including changes addressed through me. A non-admin token receives 403.

PUT replaces one collection grant. The body requires both read and write. An omitted field limit means unrestricted access for that limit:

PUT https://{EKODB_API_URL}/api/auth/keys/{key_id}/permissions/collections/users
Content-Type: application/json
Authorization: Bearer {ADMIN_TOKEN}

{
"read": true,
"write": true,
"select_fields": ["name", "email"],
"writable_fields": ["name"]
}

# Response when creating the grant
{
"before": null,
"after": {
"read": true,
"write": true,
"select_fields": ["name", "email"],
"exclude_fields": null,
"writable_fields": ["name"]
}
}

PATCH merges into an existing entry. Omitted fields retain their values; null removes a field limit; a list sets that limit. An empty list is a list, not an omitted field or null. Patching an absent entry returns 404.

PATCH https://{EKODB_API_URL}/api/auth/keys/{key_id}/permissions/collections/users
Content-Type: application/json
Authorization: Bearer {ADMIN_TOKEN}

{
"write": false,
"select_fields": null
}

DELETE /api/auth/keys/{key_id}/permissions/collections/{name} removes the entry and returns 404 if it does not exist. The response has the previous entry in before and null in after.

Set KV Permissions​

Use PUT, PATCH, or DELETE on /api/auth/keys/{key_id}/permissions/kv/{prefix}. KV bodies contain read and write flags. PUT requires at least one flag to be true; otherwise it returns 400. A PATCH that leaves neither permission removes the grant. The prefix *, in the path segment /kv/*, grants access to the whole KV namespace.

PUT https://{EKODB_API_URL}/api/auth/keys/{key_id}/permissions/kv/session%3A
Content-Type: application/json
Authorization: Bearer {ADMIN_TOKEN}

{
"read": true,
"write": true
}

A write to /permissions/kv without a prefix segment returns 405 and changes nothing. Unknown request-body fields return 400 for permission changes.

Set Function Permissions​

These checks are enforced in the default enforce mode. On an instance running in shadow mode, a function call refused for want of a call grant is recorded as access_would_deny and allowed to proceed. The admin-only grant routes below, their request validation and their 404 and 405 answers are the same in both modes. A function call grant lets a key that is not an admin call the stored functions its pattern covers. A pattern is a function label (that function only), a label prefix ending in one * such as report_*, or * for every function. An admin key calls every function and needs no grant. Use PUT or DELETE on /api/auth/keys/{key_id}/permissions/functions/{pattern}, with the pattern percent-encoded (report_* is report_%2A):

PUT https://{EKODB_API_URL}/api/auth/keys/{key_id}/permissions/functions/report_%2A
Content-Type: application/json
Authorization: Bearer {ADMIN_TOKEN}

{ "call": true }

The response has the same {before, after} shape as the other permission changes. DELETE takes the grant away, and a direct DELETE of a grant the key does not hold returns 404. call: false, a body field the route does not know, and a pattern that is not a valid grant return 400. PATCH is not a route here (405). A pattern cannot be empty or longer than 256 bytes, cannot hold * anywhere but last, cannot be exactly . or .., and cannot hold control or invisible formatting characters. Each change is written to the audit trail as function_permissions_updated. See Functions: Permissions for what a grant allows.

Encode Resource Names​

SDK permission-name arguments must contain valid Unicode text. Invalid UTF-8 and unpaired UTF-16 surrogates are rejected before an HTTP request is sent. A literal U+FFFD replacement character is valid input, subject to the name restrictions below.

Percent-encode each collection name or KV prefix as one path segment. For example, tenant:a/ becomes tenant%3Aa%2F, a space becomes %20, and + can be encoded as %2B to preserve a literal plus. Do not use form encoding that replaces spaces with +.

A name must be nonempty and cannot be . or ... Unicode control characters (category Cc) and these exact code points are rejected:

  • U+00AD, U+061C, U+180E
  • U+200B–U+200F, U+2028–U+202E
  • U+2060–U+2064, U+2066–U+2069, U+FEFF

These are selective exclusions. Other Unicode format characters (category Cf) are allowed, including U+0600, U+FFF9, and U+E0001.

When Permission Changes Take Effect​

Every permission change returns {before, after} without a token. The key's next token, obtained with POST /api/auth/token, carries the updated grants. An already-issued token retains its old grants until it expires. Re-exchange the affected key's token when the application needs to use a change immediately.

Permission Levels​

Collection Permissions​

PermissionDescriptionOperations Allowed
readView records in the collectionGET, query, search
writeCreate, update, and delete recordsPOST (insert), PUT (update), DELETE
note

There are only two collection permissions: read and write. Deleting records is governed by write (there is no separate delete permission). Granting write allows insert, update, and delete.

Admin Permissions​

Admin keys have full access to:

  • All collections (read and write)
  • Collection creation and deletion
  • Schema management
  • Index management
  • API key management
  • System administration
Security Best Practice

Use admin keys only for initial setup and administrative tasks. For application access, create API keys with minimal required permissions.

Complete Example​

This example creates a server-generated key, uses its id for permission changes and revocation, and exchanges a fresh token after a grant changes. Set EKODB_API_URL, the existing ADMIN_API_KEY, and its ADMIN_TOKEN in your shell. It does not print either secret or token, and its exit trap revokes only the created key.

#!/bin/bash
set -euo pipefail
: "${EKODB_API_URL:?Set EKODB_API_URL}"
: "${ADMIN_API_KEY:?Set ADMIN_API_KEY}"
: "${ADMIN_TOKEN:?Set ADMIN_TOKEN}"
# ekoDB serves HTTPS only. A hostname-only value gets https://; an http:// value is
# refused before any request, because curl would send the admin key and bearer token
# in plaintext.
case "$EKODB_API_URL" in
https://*) base_url="${EKODB_API_URL%/}" ;;
http://*) echo "EKODB_API_URL must use https://" >&2; exit 1 ;;
*) base_url="https://${EKODB_API_URL%/}" ;;
esac
key_id=""

cleanup() {
if [ -n "$key_id" ]; then
curl -fsS -X DELETE "$base_url/api/auth/keys/$key_id" \
-H "Authorization: Bearer $ADMIN_TOKEN" >/dev/null
fi
}
trap cleanup EXIT

# 1. Omit key so the server generates the secret and its separate id.
response=$(jq -n --arg admin_key "$ADMIN_API_KEY" '{
api_key: $admin_key,
label: "Web App Key",
description: "Scoped example key",
is_admin: false,
collection_permissions: {users: ["read"]}
}' | curl -fsS -X POST "$base_url/api/auth/register" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" --data-binary @-)
key_id=$(printf '%s' "$response" | jq -er '.id')
new_api_key=$(printf '%s' "$response" | jq -er '.key')

# 2. Exchange the new secret for a token without putting it in a URL.
token_response=$(jq -n --arg key "$new_api_key" '{api_key: $key}' | \
curl -fsS -X POST "$base_url/api/auth/token" \
-H "Content-Type: application/json" --data-binary @-)
jwt_token=$(printf '%s' "$token_response" | jq -er '.token')

# 3. Read the caller's own permission resource.
curl -fsS "$base_url/api/auth/keys/me/permissions" \
-H "Authorization: Bearer $jwt_token"

# 4. Replace a grant by id. The response is {before, after}, not a token.
curl -fsS -X PUT \
"$base_url/api/auth/keys/$key_id/permissions/collections/posts" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{"read": true, "write": false}'

# 5. Exchange again to obtain the new grants.
token_response=$(jq -n --arg key "$new_api_key" '{api_key: $key}' | \
curl -fsS -X POST "$base_url/api/auth/token" \
-H "Content-Type: application/json" --data-binary @-)
jwt_token=$(printf '%s' "$token_response" | jq -er '.token')
curl -fsS "$base_url/api/auth/keys/me/permissions" \
-H "Authorization: Bearer $jwt_token"

# The exit trap revokes the created key by id.

Best Practices​

API Key Security​

Do:

  • ✅ Store API keys securely (environment variables, secrets manager)
  • ✅ Use different keys for development, staging, and production
  • ✅ Create keys with minimal required permissions
  • ✅ Rotate keys regularly
  • ✅ Revoke keys immediately if compromised

Don't:

  • ❌ Hardcode API keys in source code
  • ❌ Commit keys to version control
  • ❌ Share admin keys with applications
  • ❌ Use the same key across multiple environments
  • ❌ Expose keys in client-side code

Permission Strategy​

Principle of Least Privilege:

# Good: Minimal permissions
{
"users": { "read": true, "write": false }, # Read-only for users
"analytics": { "read": false, "write": false } # No access to analytics
}

# Avoid: Excessive permissions
{
"users": { "read": true, "write": true }, # More than needed if you only read
"is_admin": true # Full access when not required
}

Token Lifecycle​

JWT Token Expiration:

JWT tokens expire after a period (default: 1 hour). When using direct HTTP API, implement token refresh:

# Check if token is expired
if token_expired; then
# Regenerate token
new_token=$(curl -X POST .../api/auth/token \
-d '{"api_key": "YOUR_KEY"}' | jq -r '.token')
fi
Client Libraries Handle This

When using ekoDB client libraries, token refresh is automatic. You don't need to manually check expiration.

Troubleshooting​

Common Authentication Errors​

401 Unauthorized:

{
"error": "Invalid or expired token"
}

Solution: Regenerate JWT token using your API key.

403 Forbidden:

{
"error": "No write permission for collection users"
}

Solution: Update API key permissions to include required access.

Invalid API Key:

{
"error": "API key not found or revoked"
}

Solution: Verify the API key is correct and hasn't been revoked.

Great! You can now use the JWT token to authenticate your requests to the ekoDB API.

Next, you can learn how to use the ekoDB API to manage your data!

If you have any issues, please email support@ekodb.io to create a ticket.