Building SaaS Auth from Scratch

Este post ainda não está disponível no seu idioma. Mostrando a versão em inglês.

engineering

Building SaaS Auth from Scratch

A deep dive into session management, 2FA, and magic links for multi-tenant applications

Alexandre Awadallak1 min read

Authentication is the foundation of any SaaS application. In this post, we'll walk through how AtendePraMim implements session-based auth with iron-session, 2FA via TOTP, and magic links.

Session Management#

We use iron-session with AES-256 encrypted HttpOnly cookies. No JWTs exposed to the browser.

HttpOnly cookies are invisible to JavaScript, making them immune to XSS token theft.

Two-Factor Authentication#

TOTP-based 2FA adds a second layer. The user scans a QR code with their authenticator app and enters a 6-digit code on each login.

For passwordless auth, we generate a single-use token, hash it with SHA-256, and email the user a login link.

User enters email#

The login form accepts just an email address.

Server generates token#

A crypto.randomBytes(32) token is created and hashed before storage.

The link contains the raw token. The server hashes it and looks up the match.

Conclusion#

Session-based auth with iron-session gives you the simplicity of cookies with the security of encryption. Combined with 2FA and magic links, you get a production-ready auth system.