Mahedi Hasan

Full-stack Developer

Front-end Developer

Back-end Developer

Mobile and Web App Developer

Mahedi Hasan
Mahedi Hasan
Mahedi Hasan
Mahedi Hasan
Mahedi Hasan
Mahedi Hasan
Mahedi Hasan

Full-stack Developer

Front-end Developer

Back-end Developer

Mobile and Web App Developer

Blog Post

Authentication Strategy: Top-notch Security, No Cost, Time-Efficient, Best Features

September 14, 2024 Architecture, Backend
Authentication Strategy: Top-notch Security, No Cost, Time-Efficient, Best Features

Modern applications require robust and scalable authentication mechanisms to ensure security without compromising performance or adding unnecessary costs. Many backends rely on traditional JWT token verification from their own databases. However, this method has limitations, such as the need to maintain a database and ensure its security. A better solution is to adopt a hybrid authentication strategy that combines the best features of third-party authentication providers with your own backend logic.

Proposed Solution

After spending a lot of time, reading books, talking professional, I have implemented different authentication techniques I finally came up with a hybrid solution. I am using firebase as it’s auth is completely free but you can use any other auth provider like Okta, AWS Cognito, Azure AD (now known as Entra ID) etc.

Frontend:

  • Use Firebase Authentication SDK for managing user authentication.
    • Supports various login methods: email/password, Google, Apple, GitHub, Facebook, etc.
    • Provides scalability and flexibility to add more authentication methods in the future.
    • No need to manage the complexity of password hashing or session storage.

Backend:

  • Create your own backend and connect it to your preferred database (e.g., PostgreSQL).
  • Create your user on your database. [The user id should match firebase auth user id].
  • Use Firebase for token verification while maintaining user records in your database.
  • Implement a middleware to verify incoming requests against Firebase tokens and link the user’s Firebase ID (UUID) to the corresponding database record.

Key Implementation (Backend Middleware)

The middleware ensures that every request is authenticated using Firebase tokens while enriching the request with user-specific details from the database.

Steps:

  1. Firebase token is verified to authenticate the user.
  2. Middleware fetches additional user details (permissions, role, organization) from the database.
  3. Enriched req.user object is passed to subsequent backend handlers.

Why This Approach?

  1. Cost-Effective:
    Firebase Authentication is free for many use cases, including email/password and social logins, significantly reducing the need for costly authentication services.
  2. Scalability and Flexibility:
    Firebase handles token generation, expiration, and validation, making it easy to scale without worrying about maintaining a custom authentication system.
  3. Top-notch Security:
    Firebase tokens are secure, widely trusted, and frequently updated with modern security practices. Combining this with your backend ensures an extra layer of security by validating user roles, permissions, and organizational data.
  4. Database Integration for Business Logic:
    By maintaining a database of users mapped to Firebase UUIDs, the backend can implement custom business logic, such as role-based access control (RBAC), organization-level permissions, and advanced analytics.
  5. Time Efficiency:
    Firebase’s ready-to-use authentication SDK accelerates the development process. The middleware pattern ensures seamless integration with backend APIs.
  6. Future-Proof:
    The hybrid approach allows the backend to remain agnostic of the authentication provider. If needed, Firebase can be replaced without affecting the backend database logic.

Differences Between Traditional Backend Authentication and Firebase Authentication (or Similar Services)

AspectTraditional Backend AuthFirebase Auth (or Similar Services)
Token ManagementTokens (e.g., JWT) are generated and validated by the backend itself.Tokens are generated, validated, and managed by Firebase or third-party services.
Password HandlingBackend must handle password hashing, salting, and storage securely.No password management required. Firebase securely handles all authentication flows.
Database DependencyRequires maintaining a database for user authentication and session tracking.Minimal dependency on backend databases; user authentication details are stored by the service.
Security MaintenanceDevelopers must ensure robust encryption, regular updates, and secure practices for managing tokens and passwords.The service handles security best practices, including token expiration, revocation, and two-factor authentication.
Authentication MethodsLimited to what the developer implements (e.g., username/password, OAuth).Supports multiple out-of-the-box methods like email/password, Google, Facebook, GitHub, Apple, etc.
ScalabilityThe backend must scale to handle increased authentication traffic.Firebase or similar services handle scalability and high availability automatically.
Implementation TimeRequires significant development and testing to set up and secure properly.Quick and easy to integrate with pre-built SDKs and APIs.
CostCosts are tied to hosting, maintaining, and scaling the backend.Free for most use cases (e.g., Firebase offers a generous free tier).
Session ManagementRequires custom session handling (e.g., cookies, JWTs) and logout mechanisms.Built-in session/token management with automatic logout on token expiration.
ExtensibilityAdding new login methods (e.g., OAuth providers) requires significant effort.Adding new providers is straightforward with pre-built integrations.
Role-Based Access ControlRequires custom implementation for roles and permissions.Can integrate Firebase’s Custom Claims feature for basic role management; advanced logic is handled in the backend.
Multi-Factor Authentication (MFA)Requires separate implementation for MFA like OTP or app-based verification.Provides built-in MFA features for enhanced security.
Error HandlingDevelopers must manage token errors (e.g., expiration, invalid tokens).Firebase handles most errors and provides detailed responses for developers.

Final Thoughts

Firebase Authentication (or similar services) is an excellent choice for projects that prioritize ease of use, cost efficiency, and security without the burden of managing traditional authentication systems. Traditional backend auth is better suited for projects that require complete control, customization, or self-hosted solutions but often that approach leads extra cost, outdated security. The choice is yours.

Write a comment