Email Verification Authentication: Implementation on Laravel
We often encounter tasks where standard password authentication creates more problems than it solves. Spam registrations (up to 70% of all attempts) clog the database, forgotten passwords generate a stream of support tickets, and database leaks discredit the service. Email verification authentication eliminates these risks. Significant support cost savings can be achieved by reducing support workload and decreasing fake accounts.
Why Is Email Verification Critical for Security?
Without verification, an attacker can register with any address and send spam or gain access to features that require confirmation. Verification guarantees that the user owns the mailbox. Additionally, it is the first step to account recovery and protection against account takeover. According to our project data, implementing verification reduces fake registrations by 95%.
Two Usage Scenarios
The first scenario is verification during registration. The user registers with a password, receives an email, confirms the address—only then gets full access. The second is passwordless login. The user enters their email, receives an email with a link, clicks it—authenticated without a password. Both scenarios can coexist.
How We Implement Email Verification Turnkey
Email Verification During Registration (Laravel)
The User model implements the MustVerifyEmail contract. This requires defining the sendEmailVerificationNotification() method, which sends a custom notification. We use built-in signed URLs.
class User extends Authenticatable implements MustVerifyEmail
{
public function sendEmailVerificationNotification(): void
{
$this->notify(new CustomVerifyEmailNotification());
}
}
Route::get('/email/verify/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');
The signed URL is generated with an expiration of 60 minutes. The signature is HMAC-SHA256 using the APP_KEY. Modifying parameters returns a 403.
$url = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
['id' => $user->id, 'hash' => sha1($user->email)]
);
OTP Code Instead of Link
Some projects prefer a 6-digit code—more convenient if the email is opened on another device. We cache the code hash with a 10-minute expiration and verify using hash_equals for timing attack protection.
$code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
Cache::put("email_verification:{$user->id}", hash('sha256', $code), now()->addMinutes(10));
public function verify(Request $request): JsonResponse
{
$stored = Cache::get("email_verification:{$user->id}");
if (!$stored || !hash_equals($stored, hash('sha256', $request->code))) {
return response()->json(['message' => 'Invalid or expired code'], 422);
}
$user->markEmailAsVerified();
Cache::forget("email_verification:{$user->id}");
return response()->json(['message' => 'Email verified']);
}
Spam Protection and Resend
RateLimiter is configured so that one email can be sent no more than once every 5 minutes. The frontend shows a countdown until the next send. This prevents brute force and spam attacks.
RateLimiter::for('email-verification', function (Request $request) {
return Limit::perMinutes(5, 1)->by($request->user()->id);
});
Email Change with Verification
Changing an email safely requires confirming the new address. We introduce a pending_email field in the users table or a separate table. A verification email is sent to the new address, and only after successful confirmation is the email updated.
$user->update(['pending_email' => $newEmail]);
// Send verification to $newEmail
// Upon confirmation:
$user->update(['email' => $newEmail, 'pending_email' => null]);
Queue Configuration and Monitoring
Email sending must be asynchronous to avoid blocking the response. We use the Laravel queue (Redis or SQS drivers) and configure monitoring via Horizon or Laravel Pulse. If an email is not delivered, we log the error and notify the administrator.
How We Implement Email Verification: Step-by-Step Plan
- Analyze requirements and choose the scenario (registration, passwordless, or both).
- Design the data model: add
email_verified_at, pending_email fields, configure queue relationship.
- Implement routes and controllers with signed URLs or OTP.
- Create custom email templates (HTML + plain text).
- Configure rate limiting and error handling (expired links, repeated clicks).
- Test edge cases (email change, resend, parallel requests).
- Deploy using queues and monitoring.
Comparison of OTP and Magic Link
| Criteria |
OTP Code |
Magic Link |
| Convenience on one device |
Need to open email and enter code |
Instant authentication on click |
| Security |
Time-limited code, 6 digits |
Signed URL, may be intercepted |
| Implementation |
Requires cache and hashing |
Uses signed route |
| User Experience |
Requires manual input |
Seamless |
Implementation Stages
| Stage |
Duration |
Result |
| Requirements Analysis |
0.5–1 day |
Scenario selected (registration/passwordless) |
| Design |
0.5–1 day |
Model, routes, controllers, templates |
| Core Implementation |
0.5–1 day |
email_verified_at, pending_email fields |
| Notification Setup |
0.5–1 day |
Custom email with link or OTP |
| Security and Testing |
1–2 days |
Rate limiting, signed URL, edge cases |
| Deployment |
0.5 day |
Queue, monitoring, documentation |
Handling Expired Links
If the user clicks an expired link, we return a clear message with a "Resend email" button. If they click an already confirmed link, we return a 200 with a notification that the email is already verified.
Common Mistakes and Their Solutions
-
Expired link: display a message and offer to resend.
-
Repeated click on link: return 200 with a notification that the email is already verified.
-
Missing queue: sending emails synchronously slows the response—we use the Laravel queue.
What You Get as a Result
- Complete source code with comments (models, controllers, notifications).
- Custom email templates adapted to your brand.
- Queue and monitoring configuration (Laravel Horizon/Pulse).
- Developer documentation for deployment and maintenance.
- 30-day guarantee and support after implementation.
Contact us for a consultation—we will assess your project and offer an optimal solution. Order a turnkey implementation and get a ready-made authentication system in the shortest possible time.
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
- Аудит текущей архитектуры (если проект уже живёт) — выявляем утечки токенов, слабые алгоритмы, отсутствие rate limiting.
- Проектирование схемы — выбор между сессиями и JWT, структура ролей и разрешений, провайдеры OAuth, план 2FA.
- Реализация — пишем код с покрытием тестов (unit + integration + security).
- Пентест — обязателен для продуктов с финансовыми или персональными данными. Проводим автоматическое и ручное тестирование.
- Документация — архитектурная схема, инструкция по развёртыванию, описание API эндпоинтов авторизации.
- Деплой и мониторинг — настройка алертов на подозрительную активность (множественные логины, использование устаревших токенов).
- Пост-релизная поддержка — 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-логики или разработку с нуля — напишите нам.