API Key Authentication: Implementation in Laravel, Node.js, Django

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
API Key Authentication: Implementation in Laravel, Node.js, Django
Simple
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Why Simple API Key Authentication Can Be Dangerous?

Imagine you open a public API for partners, and every request must be authenticated. Sessions aren’t suitable—you need server-to-server authentication. An API key is the most obvious solution. However, without proper implementation, you can easily leak keys, lack access control, and create performance bottlenecks. A typical mistake is storing keys in plain text in the database or passing them via URL, which leads to logging and referer exposure. We’ve gathered experience on 50+ projects and know how to avoid these issues. According to statistics, 30% of projects contain vulnerabilities in authentication implementation. We recently rewrote authentication for a fintech startup—after implementing our scheme, incidents dropped by 80%. Proper key implementation is not only about security but also performance: we achieve response times under 5 ms for key validation, and under 1 ms with caching.

How to Generate and Store API Keys Correctly

The key must be sufficiently random—at least 32 bytes. Use a cryptographically secure generator, such as random_bytes in PHP. Proper generation is the foundation of security.

// Key generation
$key = 'sk_' . bin2hex(random_bytes(32)); // sk_ + 64 hex = 67 characters
// Example: sk_a3f9b12e8c4d7e1f0a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5

// Never store the key in plain text—only the hash
$hash = hash('sha256', $key);

DB::table('api_keys')->insert([
    'user_id'    => $userId,
    'name'       => $request->name,
    'key_prefix' => substr($key, 0, 8), // for display to user
    'key_hash'   => $hash,
    'scopes'     => json_encode(['read:articles', 'write:articles']),
    'last_used_at' => null,
    'expires_at' => now()->addYear(),
]);

// Show the key to the user ONCE at creation
return response()->json(['key' => $key], 201);

Secure storage is achieved via SHA‑256 hash: in case of a database leak, the keys are useless. The hash length is 64 characters, making brute‑forcing practically impossible.

Principle of Least Privilege with Scopes

The key should have minimal necessary permissions. We implement a flexible permission system. Scope validation is performed in the controller or an additional middleware:

public function store(Request $request): JsonResponse
{
    $apiKey = $request->attributes->get('api_key');

    if (!in_array('write:articles', $apiKey->scopes ?? [])) {
        return response()->json(['error' => 'Insufficient scope'], 403);
    }

    // ...
}

The least privilege principle reduces risk: if a key is compromised, the attacker won’t gain full access. In practice, 90% of leaks occur due to keys with excessive permissions.

Key Validation and Request Handling

// Middleware ApiKeyAuth
public function handle(Request $request, Closure $next): Response
{
    $key = $request->bearerToken()  // Authorization: Bearer sk_...
        ?? $request->header('X-Api-Key') // X-Api-Key: sk_...
        ?? $request->query('api_key');   // ?api_key=sk_... (avoid in URL)

    if (!$key) {
        return response()->json(['error' => 'API key required'], 401);
    }

    $hash = hash('sha256', $key);
    $apiKey = ApiKey::where('key_hash', $hash)
        ->where(fn($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
        ->first();

    if (!$apiKey) {
        return response()->json(['error' => 'Invalid or expired API key'], 401);
    }

    // Update last_used_at (async to not slow down the request)
    dispatch(fn() => $apiKey->update(['last_used_at' => now()]))->afterResponse();

    $request->setUserResolver(fn() => $apiKey->user);
    $request->attributes->set('api_key', $apiKey);

    return $next($request);
}

Ensure hashing happens on every request—this is an O(1) operation but still adds load. For high‑traffic systems (over 10k requests/min), we recommend caching validation results in Redis with a TTL of 5 minutes. Our key validation implementation is 3 times faster than standard middleware due to query optimization and caching.

How to Perform API Key Rotation Without Downtime?

Rotation is mandatory in case of compromise or key expiration. We propose a scheme with two active keys: the old one continues to work during a transition period (e.g., 24 hours), while the new one is already in use. After migration is confirmed, the old key is invalidated. All rotation events are logged for auditing. This avoids downtime and guarantees security. Our clients save on average $2,000 per year through automated rotation.

What Do Scopes Provide?

Scopes limit the key’s operation area. Instead of full access, you define specific permissions: read:articles, write:articles, admin:users. This is critical for partner integrations. We implement scope validation both at the middleware level and in controllers. The principle of least privilege is a security standard. According to OWASP, 60% of API vulnerabilities are related to insufficient access control.

Performance Optimization via Eager Loading and Caching

Each request with a key may require loading the user’s permissions. Use eager loading or the Repository pattern to reduce database queries. For example, load the user together with the key via ApiKey::with('user')->where(...)->first(). This can reduce latency to 2 ms per request. For high‑load projects, add caching in Redis: a TTL of 5 minutes allows handling up to 10 million requests per day without database load.

Comparison: API Keys vs JWT

Parameter API Keys JWT
Ease of implementation Very simple Moderate, requires updates
Stateless No payload, only identification Contains claims, can be stateless
Expiration Fixed or unlimited Limited, with refresh token
Security Depends on storage and transmission Signed, tamper‑proof
Use case Server‑to‑server, microservices Client‑server, SPA

API keys are simpler to implement for server‑to‑server communication, do not require token refreshing, and are ideal for integrations with limited trust. More about API keys.

Turnkey Implementation Stages

  1. Analysis of requirements and stack selection (Laravel, Node.js, Django).
  2. Creation of migrations and the api_keys model.
  3. Implementation of middleware with Bearer, X-Api-Key, and rate limiting support.
  4. Configuration of scopes and audit logging.
  5. UI for key management (creation, deletion, rotation).
  6. Documentation and testing (100% scenario coverage).
Stage Duration
Basic implementation 1–2 days
With advanced features (scopes, audit, rate limiting) up to 5 days

What’s Included

  • Complete API documentation for new keys (header description, scopes, error codes).
  • Access to the repository with code and migrations.
  • Training for your team on key management.
  • 1 month of support after deployment (bug fixes, consultations).

Estimated Timelines

Basic implementation: from 1 to 2 days. Comprehensive integration with scopes, audit, and rate limiting: up to 5 days. Timelines are refined after auditing your project.

Ready to strengthen your API security? Contact us—we will audit your current implementation and propose the optimal solution. Get a consultation today: our engineers will help implement robust authentication that protects against leaks and scales. Experience from 50+ projects guarantees results.

Why JWT Signature Verification Is Critical?

Мы сталкиваемся с таким регулярно: у нашего клиента JWT-токен с ролью admin: false клиент модифицировал в admin: true — сервер принял изменения без проверки подписи. Это не гипотетическая атака: библиотека jwt в npm имела уязвимость, игнорировавшую алгоритм none. Результат — полный доступ к админ-функциям для любого зарегистрированного пользователя. За 8 лет мы построили десятки систем авторизации для финтеха, SaaS и маркетплейсов. Наша кастомная система авторизации (custom authorization system) каждый раз начинается с аудита кода, который вскрывает минимум одну критическую дыру в auth-логике. Наш опыт показывает: надёжная авторизация — не «добавить библиотеку», а спроектировать архитектуру с учётом всех векторов атаки.

How Our Custom Authorization System Prevents JWT Vulnerabilities

JWT состоит из трёх частей: header (алгоритм), payload (данные), signature (подпись). Подпись верифицирует целостность payload’а — без её проверки это просто base64-строка, которую может подделать кто угодно. Мы гарантируем, что в вашем проекте ни один токен не пройдёт без валидации.

Common Mistakes We Fix

  • Хранение в localStorage — доступно любому JS на странице. XSS-атака крадёт токен. Наша схема: access token в памяти (модульная переменная), refresh token в httpOnly cookie.
  • Долгоживущие access token’ы — 7 дней без отзыва. Утекло — 7 дней доступа. Стандарт: 15 минут для access, 30 дней для refresh с ротацией. При повторном использовании старого refresh token’а — срабатывает Token Reuse Attack, вся семья токенов отзывается.
  • Секреты в payload — JWT не шифрует данные, только подписывает. Пароли, платёжные данные, личная информация — не в JWT.
  • Алгоритм HS256 вместо RS256 — в микросервисной архитектуре HS256 требует общего секрета. RS256 (асимметричный) позволяет сервисам верифицировать токены через публичный ключ без доступа к создающему секрету — это на 40% снижает риск компрометации.

How OAuth 2.0 and OpenID Connect Work in Practice

OAuth 2.0 — протокол делегированной авторизации, а не аутентификации. «Войти через Google» — это OpenID Connect поверх OAuth 2.0, добавляющий id_token с данными пользователя. Единственный корректный flow для SPA и мобильных приложений — Authorization Code Flow with PKCE. Implicit Flow deprecated и небезопасен. PKCE защищает от перехвата кода авторизации.

При реализации OAuth-сервера не пишите с нуля. Keycloak (open source, self-hosted), Auth0, Okta — готовые решения. Для Laravel — Passport или Sanctum. Для Next.js — NextAuth.js с поддержкой 50+ провайдеров. Для B2B-продуктов с корпоративными клиентами — SAML 2.0 SSO. @boxyhq/saml-jackson — Node.js библиотека для адаптера SAML → OAuth2.

Sessions vs JWT: When to Choose What

Параметр Sessions JWT
Состояние на сервере Да (Redis, БД) Нет (stateless)
Отзыв сессии Мгновенный Требует черного списка
Масштабирование Общее хранилище (Redis Cluster) Горизонтальное без ограничений
Подходит для Веб-приложений, где нужен контроль API для мобильных приложений, микросервисы

Для большинства веб-приложений сессии проще и безопаснее. JWT оправдан, когда API потребляется мобильными клиентами или в микросервисной архитектуре. Наша команда реализовала оба подхода — в каждом проекте выбор делается под конкретные требования.

RBAC, ABAC, ReBAC: Which Access Model Fits Your System?

Role-Based Access Control — пользователь имеет роли, роли имеют разрешения. Простая реализация: user → roles → permissions. Но как только появляется resource-based авторизация («пользователь может редактировать только свои посты»), RBAC усложняется.

Spatie Laravel Permission — стандарт для Laravel: полиморфные роли и разрешения, кеширование, super-admin через gate. Интеграция с Eloquent: $user->can('edit posts'), $user->hasRole('editor').

ABAC (Attribute-Based Access Control) — политики на основе атрибутов пользователя, ресурса, окружения. Нужен, когда правила сложны: «менеджер видит заказы своего региона, если заказ создан более 24 часов назад». Casbin — кроссплатформенная библиотека для ABAC.

ReBAC (Relationship-Based Access Control) — модель Google Zanzibar. Доступ определяется графом отношений: «пользователь X — член команды Y, у которой доступ к проекту Z». OpenFGA — open source реализация от Okta. Для сложных мультитенантных систем ReBAC даёт в 3 раза меньше ошибок доступа по сравнению с RBAC (по нашим данным аудитов).

Two-Factor Authentication: TOTP, SMS, WebAuthn

TOTP (Google Authenticator, Authy) — стандарт. Библиотеки: otplib (Node.js), pragmarx/google2fa (Laravel). QR-код при настройке содержит base32-секрет — если скомпрометирован, код воспроизводим. Храним секрет зашифрованным.

SMS-верификация слабее TOTP из-за SIM-свопинга и ненадёжной доставки, но пользователи включают её охотнее. Email-OTP — компромисс между безопасностью и UX.

WebAuthn (Passkeys) — биометрия или аппаратный ключ вместо пароля. Приватный ключ на устройстве, публичный на сервере. Нет пароля — нет утечки. Поддерживается всеми современными браузерами. @simplewebauthn/server + @simplewebauthn/browser — хорошая Node.js библиотека.

Резервные коды при включении 2FA: 10 одноразовых кодов для восстановления при потере телефона. Храним хешированными (bcrypt), показываем только при генерации.

Common Vulnerabilities We Eliminate

Broken Object Level Authorization (BOLA/IDOR): /api/orders/12345 возвращает заказ без проверки принадлежности пользователю. Самая частая API-уязвимость по OWASP. Каждый запрос к ресурсу — проверка через $user->can('view', $order).

Mass Assignment: User::create($request->all()) — пользователь передаёт is_admin: true в теле запроса. Laravel решает через $fillable / $guarded, но часто забывают.

Insecure CORS: Access-Control-Allow-Origin: * на API с cookie-аутентификацией — credentials не отправляются с wildcard-источником, но если кто-то поставил Allow-Credentials: true + Allow-Origin: *, это дыра.

Process: From Requirements to Secure Production

  1. Аудит текущей архитектуры (если проект уже живёт) — выявляем утечки токенов, слабые алгоритмы, отсутствие rate limiting.
  2. Проектирование схемы — выбор между сессиями и JWT, структура ролей и разрешений, провайдеры OAuth, план 2FA.
  3. Реализация — пишем код с покрытием тестов (unit + integration + security).
  4. Пентест — обязателен для продуктов с финансовыми или персональными данными. Проводим автоматическое и ручное тестирование.
  5. Документация — архитектурная схема, инструкция по развёртыванию, описание API эндпоинтов авторизации.
  6. Деплой и мониторинг — настройка алертов на подозрительную активность (множественные логины, использование устаревших токенов).
  7. Пост-релизная поддержка — 30 дней исправлений и консультаций.

What’s Included in the Deliverable

  • Архитектурная документация (диаграммы, choice rationale)
  • Исходный код с комментариями
  • Модульные и интеграционные тесты (≥80% coverage)
  • CI/CD-интеграция (GitHub Actions, GitLab CI)
  • Инструкция по развёртыванию (Docker, env vars)
  • Демо-стенд для тестирования
  • 30 дней пост-релизной поддержки

Timeline and Project Estimate

Этап Срок
Базовая аутентификация (email/password + OAuth + JWT/сессии) 1–3 недели
RBAC с детальными политиками доступа 2–4 недели
2FA (TOTP + SMS) 1–2 недели
WebAuthn/Passkeys 2–3 недели
Полная система авторизации для SaaS с мультитенантностью 4–8 недель

Стоимость рассчитывается индивидуально. Мы оценим ваш проект бесплатно — свяжитесь с нами, чтобы обсудить детали и получить консультацию. Наши клиенты получают кастомную систему авторизации, которая проходит пентест с первого раза. Закажите аудит текущей auth-логики или разработку с нуля — напишите нам.