Authentication

SmartElektroHub supports two authentication methods: API Keys for server-side integrations and OAuth 2.0 when building third-party applications on behalf of other SmartElektroHub accounts.

API Keys

Every SmartElektroHub account has two types of API key, available in the Dashboard → Settings → API Keys section:

Key typePrefixWhere to use
Secret Key eh_sk_… Server-side only. Full API access. Never expose publicly.
Publishable Key eh_pk_… Safe for browser / mobile apps. Read-only scope + subscriber token creation.

Using an API key

Pass the key in the Authorization header as a Bearer token:

curl https://api.smart-elektro.ru/v2/streams \
  -H "Authorization: Bearer eh_sk_••••••••••••••••"
// JavaScript SDK — key is passed at initialization
const client = new SmartElektroHub({ apiKey: 'eh_sk_••••••••••••••••' });
Never commit API keys to source control. Use environment variables or a secrets manager. Rotate a compromised key immediately from the Dashboard.

Rotating keys

To rotate a key, open Dashboard → Settings → API Keys, click Roll key, and update your environment variables. Old keys are invalidated immediately.

OAuth 2.0

Use the Authorization Code flow when your application acts on behalf of other SmartElektroHub accounts (e.g., a third-party dashboard or integration platform).

1 — Redirect the user

GET https://auth.smart-elektro.ru/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https%3A%2F%2Fyourapp.example%2Fcallback
  &response_type=code
  &scope=streams%3Aread%20streams%3Awrite%20reports%3Aread
  &state=RANDOM_CSRF_TOKEN

2 — Exchange the code for tokens

curl -X POST https://auth.smart-elektro.ru/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE_FROM_REDIRECT" \
  -d "redirect_uri=https://yourapp.example/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

Token response

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "rt_01kp27cxn8jm4tqbvz9r3wf",
  "scope": "streams:read streams:write reports:read"
}

3 — Refresh an access token

curl -X POST https://auth.smart-elektro.ru/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=rt_01kp27cxn8jm4tqbvz9r3wf" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"
Access tokens expire after 60 minutes. Refresh tokens expire after 90 days or when used to obtain a new refresh token. Store refresh tokens securely server-side.

Available scopes

ScopeAccess granted
streams:readList and retrieve streams
streams:writeCreate, update, and delete streams
reports:readList and retrieve reports and records
reports:writeCreate, update, and publish records
webhooks:readList webhook configurations
webhooks:writeCreate and delete webhook configurations
account:readRead account and billing information

Authentication Errors

CodeStatusMeaning
missing_token401No Authorization header provided
invalid_token401Token malformed or signature invalid
token_expired401Access token has expired — refresh it
insufficient_scope403Token lacks required scope for this action
key_revoked401API key has been revoked

Аутентификация

SmartElektroHub поддерживает два метода аутентификации: API-ключи для серверных интеграций и OAuth 2.0 — когда ваше приложение действует от имени других аккаунтов SmartElektroHub.

API-ключи

В каждом аккаунте SmartElektroHub есть два типа ключей — в разделе Dashboard → Settings → API Keys:

Тип ключаПрефиксГде использовать
Секретный ключ eh_sk_… Только на сервере. Полный доступ к API. Никогда не раскрывайте публично.
Публичный ключ eh_pk_… Безопасен для браузера и мобильных приложений. Только чтение + создание токенов подписчика.

Использование API-ключа

Передайте ключ в заголовке Authorization как Bearer-токен:

curl https://api.smart-elektro.ru/v2/streams \
  -H "Authorization: Bearer eh_sk_••••••••••••••••"
// JavaScript SDK — ключ передаётся при инициализации
const client = new SmartElektroHub({ apiKey: 'eh_sk_••••••••••••••••' });
Никогда не коммитьте API-ключи в систему контроля версий. Используйте переменные окружения или менеджер секретов. При компрометации ключа немедленно смените его в Dashboard.

Ротация ключей

Для смены ключа перейдите в Dashboard → Settings → API Keys, нажмите Сменить ключ и обновите переменные окружения. Старые ключи аннулируются немедленно.

OAuth 2.0

Используйте поток Authorization Code, когда ваше приложение действует от имени других аккаунтов SmartElektroHub (например, сторонний дашборд или платформа интеграций).

1 — Перенаправьте пользователя

GET https://auth.smart-elektro.ru/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https%3A%2F%2Fyourapp.example%2Fcallback
  &response_type=code
  &scope=streams%3Aread%20streams%3Awrite%20reports%3Aread
  &state=RANDOM_CSRF_TOKEN

2 — Обменяйте код на токены

curl -X POST https://auth.smart-elektro.ru/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE_FROM_REDIRECT" \
  -d "redirect_uri=https://yourapp.example/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

Ответ с токенами

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "rt_01kp27cxn8jm4tqbvz9r3wf",
  "scope": "streams:read streams:write reports:read"
}

3 — Обновление access-токена

curl -X POST https://auth.smart-elektro.ru/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=rt_01kp27cxn8jm4tqbvz9r3wf" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"
Access-токены действительны 60 минут. Refresh-токены — 90 дней или до момента использования для получения нового refresh-токена. Храните refresh-токены защищённо на серверной стороне.

Доступные скоупы

СкоупПредоставляемый доступ
streams:readПросмотр списка и данных потоков
streams:writeСоздание, обновление и удаление потоков
reports:readПросмотр отчётов и записей
reports:writeСоздание, обновление и публикация записей
webhooks:readПросмотр настроенных вебхуков
webhooks:writeСоздание и удаление вебхуков
account:readИнформация об аккаунте и биллинге

Ошибки аутентификации

КодСтатусОписание
missing_token401Заголовок Authorization не предоставлен
invalid_token401Токен повреждён или подпись недействительна
token_expired401Срок действия access-токена истёк — обновите его
insufficient_scope403Токен не имеет нужного скоупа для данного действия
key_revoked401API-ключ был отозван