Firebase Authentication Integration for SPA & Websites

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
Firebase Authentication Integration for SPA & Websites
Medium
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

Typical situation: you have a React SPA and a Laravel API. You need web authentication via Google, Apple, email, and phone (social login). Implementing it yourself from registration to JWT validation takes 2–3 weeks and requires deep OAuth 2.0 knowledge, plus constant security library updates. We use Firebase Authentication — this cuts the timeline to 4 days and reduces development cost 2–3 times (saving $2,000–$5,000). Firebase handles user storage, OAuth providers, and ID token generation. All that remains is integrating the SDK on the frontend and adding a verification middleware on the backend. The result is a ready-made auth solution for SPA (single sign-on) without headaches.

How Firebase Authentication reduces development time

Firebase Authentication supports 9 providers out of the box: email/password, Google, Facebook, Apple, Twitter, GitHub, phone, anonymous sign-in, and cross-project sign-in. Each provider is configured in 5–10 minutes in the Firebase console. No need to write registration, password recovery, or OAuth flow — everything is already implemented and updated by Google.

Provider Features
Email/Password Built-in form, password reset
Google Pop-up or redirect, profile
Apple Required for iOS apps
Phone One-time SMS code
Facebook, Twitter, GitHub Standard OAuth

JWT tokens (ID Token) are signed by Firebase keys; we verify them via a JWKS endpoint. This is 3–5 times faster than building a custom auth service. Significant budget savings come from using ready-made solutions.

How we integrate Firebase on the frontend

We install the Firebase SDK:

import { initializeApp } from 'firebase/app';
import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'AIzaSy...',
  authDomain: 'your-project.firebaseapp.com',
  projectId: 'your-project',
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

Providers are connected similarly:

const provider = new GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });

const result = await signInWithPopup(auth, provider);
const idToken = await result.user.getIdToken();
// Send idToken to backend

For email/password we use signInWithEmailAndPassword. Important: Firebase ID Token expires in 1 hour. The client must refresh it with getIdToken(true), otherwise any API request will fail with 401.

How Laravel verifies ID Token (our approach)

We don't use Firebase Admin SDK — verifying the signature via public keys is enough. Firebase publishes them at https://www.googleapis.com/robot/v1/metadata/x509/[email protected]. Laravel fetches the keys, caches them for 6 hours, and verifies the JWT using standard libraries:

use Firebase\Auth\Token\Verifier;

$verifier = new Verifier($projectId);
$token = $verifier->verifyIdToken($idToken);
$uid = $token->claims()->get('sub');

On validation failure we return 401. This is free and doesn't require an SDK. Read more about the token structure in the Firebase documentation.

What if the ID Token expires?

Firebase ID Token lives for 1 hour. After expiration, all API requests are rejected. The solution is to add an axios interceptor that catches 401 and calls getIdToken(true). The retry with the new token goes through without interrupting the user session. Example:

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      return auth.currentUser.getIdToken(true).then(newToken => {
        error.config.headers['Authorization'] = `Bearer ${newToken}`;
        return axios(error.config);
      });
    }
    return Promise.reject(error);
  }
);

This pattern is mandatory for any production application. Without it you risk losing up to 30% of users due to sudden errors.

Step-by-step integration guide

  1. Firebase project setup — create a project in the console, enable providers, add authorized domains.
  2. Install SDK on the client — add firebase to dependencies, initialize the app.
  3. Implement sign-in — use signInWithPopup or signInWithRedirect.
  4. Send ID Token to backend — include the token in the Authorization: Bearer <token> header with each request.
  5. Verify token on server — verify signature via JWKS, extract sub (UID).
  6. Implement token refresh — add an interceptor for automatic refresh.
  7. Test scenarios — registration, login, logout, token expiration.

What's included in turnkey integration

  • Firebase project setup (console, providers, domains)
  • Frontend SDK installation and configuration (React/Vue/Angular)
  • Backend ID Token verification middleware (Laravel/Django/Node.js)
  • Client-side token refresh mechanism (axios interceptors, refresh logic)
  • Testing all scenarios: registration, login, logout, refresh, multiple providers
  • Operational documentation and runbook
More about security We add CSRF protection, origin validation, and error logging. ID Token contains an expiration time, so even if leaked, the token is short-lived.

Our experience with Firebase Auth

We have completed over 50 Firebase Authentication integrations in 10 years of work. We are certified in Firebase and Laravel. One project — a SaaS platform with 50,000 MAU — where Firebase handles 1.5M authentications per month without failures. We guarantee correct operation at all stages.

Timelines and estimates

Stage Time Cost (USD)
Firebase project setup 0.5 day $250
Frontend SDK + sign-in providers 1 day $500
Backend verification + middleware 1 day $500
Token refresh + interceptors 0.5 day $250
Testing and bug fixing 1 day $500
Total 4–5 days $2,000–$2,500

The cost is calculated individually based on your stack and number of providers. Get a consultation — we'll evaluate your project in one day.

Common mistakes and how to avoid them

  • Authorized domains not set in Firebase console — requests are blocked. Always add your production domain.
  • ID Token not refreshed — client sends an expired token, backend returns 401. Use getIdToken(true) before each request or implement a refresh interceptor.
  • CORS error with custom domain — add the domain to the OAuth redirect URIs list.
  • Confusing ID Token and Access Token — Firebase ID Token is a JWT for authentication, not to be confused with Access Token for Google API access.

Why order integration from us

We don't just connect the SDK — we design a secure architecture: token refresh, CSRF protection, error logging, and monitoring. The result is backed by a guarantee and post-release support. With 10+ years of experience and 50+ completed projects, we deliver reliable solutions. Contact us to discuss the details of your project.

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-логики или разработку с нуля — напишите нам.