Skip to content
← All articles
10 min read

Session vs JWT authentication in SaaS: architecture, storage, and security

For most web SaaS applications, server-side sessions stored in a database and delivered via secure HttpOnly cookies outperform stateless JWTs. Sessions guarantee instant token revocation, straightforward multi-device control, and zero token exposure to browser JavaScript. Stateless JWTs shine primarily in decoupled microservices. Below is our engineering guide to session vs JWT authentication, secure cookie flags, password hashing with argon2id, 2FA, and deciding between custom Go auth and managed providers.

Authentication vs authorization: identity and tenant context

Before picking a storage mechanism or signing tokens, distinguish authentication from authorization. Authentication (AuthN) proves identity: it verifies that the entity sending requests owns the claimed user account via a password, OAuth callback, or one-time code. Authorization (AuthZ) verifies permissions: it determines whether that authenticated user can read an invoice, invite a team member, or delete a workspace.

In multi-tenant SaaS, this separation becomes critical. A single human user often belongs to multiple tenant organizations, holding distinct roles in each. When authenticating, the system establishes a global identity (user ID). When authorizing API requests, the backend resolves the tenant context (organization ID) and enforces access control rules. Tightly coupling tenant roles directly into static authentication tokens causes permission drift whenever an administrator updates user rights. Learn more about designing scalable permission hierarchies in our guide to SaaS roles and permissions.

Isolating authentication state from tenant data also safeguards data boundaries across companies sharing common infrastructure. A robust multi-tenant design verifies that every active session maps cleanly to a valid tenant membership before executing any business logic. For architectural patterns on data segregation, see our breakdown of multi-tenant SaaS architecture.

  • Authentication establishes who the user is: verified email, unique user ID, and active account status.
  • Authorization decides what the user can do: role checks, feature flags, and tenant workspace scoping.
  • Tenant context resolution: mapping the authenticated user to an active organization via request headers or route parameters.
  • Permission invalidation: role changes must take effect immediately without requiring the user to log out and log in again.

Session vs JWT authentication: architectural trade-offs and revocation

The debate between stateful sessions and JSON Web Tokens (JWT) centers on where state lives and how revocation works. A traditional session generates a cryptographically random string (an opaque token), saves it in a database table or Redis cache alongside the user ID, and sends it to the browser. On every request, the backend loads the session record, validates its expiration date, and retrieves current user attributes.

A stateless JWT encapsulates user claims, an issuance timestamp, and an expiration time directly inside a cryptographically signed payload. The server validates the cryptographic signature using a secret or public key without querying a database. While this eliminates a database query per request, it introduces a dangerous operational flaw: you cannot instantly revoke a stateless token. If a laptop is stolen, an employee is terminated, or a subscription is suspended, a stateless JWT remains fully valid until its expiration timestamp arrives.

To revoke compromised JWTs, engineering teams frequently build server-side token blacklists or short-lived token rotation mechanisms. However, querying Redis on every request to check whether a JWT is blacklisted completely destroys the stateless premise of JWTs. At that point, you have built a more complex, heavier version of server sessions without the operational simplicity of opaque identifiers.

  • Opaque sessions: small 32-byte random token, instant database revocation, clean audit log of active devices, requires a fast database or cache lookup.
  • Stateless JWT: self-contained claims, no database hit for read verification, but impossible to revoke immediately without maintaining a central revocation list.
  • Payload size: a session cookie carries only a short identifier, whereas a JWT carries its claims and signature on every request.
  • Recommendation for web SaaS: default to opaque server-side sessions stored in PostgreSQL or Redis unless you run separate third-party API clients or decoupled microservices.

Where to store authentication tokens: HttpOnly cookies, SameSite, and CSRF

Where you store the authentication credential in the browser dictates your vulnerability to cross-site scripting (XSS) and cross-site request forgery (CSRF). Storing tokens in browser LocalStorage or SessionStorage is inherently dangerous for web applications. Any third-party JavaScript library, analytics script, or injected dependency compromised by XSS can execute localStorage.getItem() and exfiltrate credentials directly to an attacker's server.

The standard industry pattern for web applications is an HttpOnly cookie. When a cookie has the HttpOnly flag set, browser JavaScript cannot read or modify it through document.cookie, completely neutralizing token theft via XSS. Combine this with the Secure flag so the browser never transmits the cookie over unencrypted HTTP connections, and set Path=/ with a strict domain scope to prevent cookie leakage across unrelated subdomains.

Because browsers automatically attach cookies to cross-origin requests, cookie-based authentication requires defense against CSRF. Modern web architectures rely primarily on the SameSite attribute. Setting SameSite=Lax ensures the browser withholds the cookie on cross-site sub-requests (such as embedded images or forms) while allowing safe top-level navigations. For state-modifying actions (POST, PUT, DELETE), pairing SameSite=Lax with origin verification (Origin and Referer headers) or standard anti-CSRF double-submit tokens provides rock-solid defense-in-depth.

  • HttpOnly flag: blocks client-side scripts from accessing the authentication token, mitigating token exfiltration via XSS.
  • Secure flag: guarantees the cookie is transmitted strictly across HTTPS connections, preventing man-in-the-middle sniffing.
  • SameSite=Lax or Strict: prevents the browser from attaching authentication cookies to malicious cross-site POST submissions.
  • CSRF double-submit token or Origin verification: mandatory additional safeguard for all mutation endpoints in web dashboards.

Password security and account recovery: argon2id and secure reset flows

Passwords must never be stored in plain text or with obsolete algorithms like MD5, SHA-1, or plain SHA-256. Modern password storage requires memory-hard and computationally expensive key derivation functions designed to withstand specialized GPU and ASIC cracking rigs. Today, the leading industry standard is argon2id, which combines resistance to side-channel cache attacks with defense against brute-force hardware cracking. Where argon2id is unavailable or legacy compatibility is needed, bcrypt remains a respectable alternative.

In Go, the official golang.org/x/crypto/argon2 package makes hashing straightforward. When configuring argon2id, tune parameters for memory usage, time iterations, and parallelism according to your server capacity. Always generate a cryptographically random 16-byte salt for every individual password. Compare supplied credentials against stored hashes using constant-time evaluation to eliminate timing side-channel vulnerabilities.

Password reset workflows represent a primary target for account takeovers. When a user requests a reset, generate a high-entropy random token using Go's crypto/rand. Never store the raw token in the database. Instead, store a SHA-256 hash of the token alongside a short expiration time (TTL of 15 to 30 minutes) and the user ID. Send the plaintext token in the email link. When the user submits a new password, hash the incoming token and look up the record. Once used, delete or invalidate the token immediately.

  • Argon2id hashing: memory-hard, highly tunable, resistant to GPU attacks; generate an isolated salt per password.
  • Bcrypt alternative: standard cost factor, supported everywhere, but lacks memory-hardness protections.
  • Hashed reset tokens: store only cryptographic hashes of reset tokens at rest; plaintext tokens live exclusively in outbound emails.
  • Strict TTL and single-use: expire password reset and magic links within 15 to 30 minutes, invalidating them immediately upon successful submission.

OAuth2 social login and two-factor authentication (2FA)

Social authentication like "Sign in with Google" or "Sign in with GitHub" lowers onboarding friction for B2B SaaS. Under the hood, this relies on OAuth2 authorization code grants. Security in OAuth2 hinges on two critical controls: the state parameter and PKCE (Proof Key for Code Exchange). The state parameter is an opaque, cryptographically random string stored in an ephemeral cookie and validated on the callback URL to prevent CSRF login attacks.

Account linking requires strict validation. When a user authenticates via Google, your backend must verify that Google confirmed the email address. Never automatically merge an OAuth profile into an existing password-based account unless the incoming identity provider guarantees email verification. Without this check, an attacker could register an unverified Google account using a victim's work email and hijack their SaaS workspace.

Two-Factor Authentication (2FA) adds an indispensable security layer for administrative and business-critical accounts. The most practical standard is Time-based One-Time Passwords (TOTP, RFC 6238). When enabling 2FA, generate a cryptographically random secret key, store it encrypted in the database, and present it as a QR code for authenticator apps. During verification, allow a small time drift window (typically one step before and after the current 30-second window) and issue a set of hashed single-use recovery codes for emergency access.

Brute-force protection, login rate limits, and session invalidation

Authentication endpoints are public by definition, making them vulnerable to automated credential stuffing, dictionary attacks, and denial-of-service attempts. Relying solely on CAPTCHA degrades user experience. Instead, implement a multi-layered rate limiting strategy that restricts attempts both by client IP address and by target email address. For techniques on stopping automated abuse at the form layer, explore our recommendations on form spam protection.

In a Go backend, implement rate limiting using token bucket or sliding window counters in Redis or memory. If an IP sends repeated failed requests, throttle responses with HTTP 429 Too Many Requests and an exponential backoff header. Avoid account lockouts that can be weaponized into denial-of-service attacks against legitimate executives; instead, enforce progressive delays, temporary IP blocks, and mandatory email verification when suspicious patterns emerge. For structured throttling architecture, read our guide to API rate limits and backoff strategies.

Comprehensive session management requires granular invalidation. Users need the ability to review all active sessions (showing device type, IP address, and last active timestamp) and terminate individual devices or log out everywhere at once. When a user changes their password, resets 2FA, or when an organization administrator revokes an employee's access, the backend must immediately revoke all associated active sessions in the database.

  • Dual-key rate limiting: track request volume simultaneously by IP address and targeted account identifier.
  • Exponential backoff: lengthen wait times progressively after repeated failed attempts to defeat automated scripts.
  • Multi-device visibility: store device user-agent and IP metadata to display transparent active session lists to users.
  • Event-driven revocation: invalidate active sessions immediately upon password changes, security setting updates, or tenant offboarding.

Build vs buy: custom Go authentication vs managed identity providers

Founders and engineering leads must decide whether to implement authentication internally or subscribe to managed identity platforms like Auth0, Clerk, Supabase Auth, or WorkOS. Managed providers offer pre-built UI components, multi-factor support, and turnkey enterprise SSO (SAML/Okta). However, they introduce significant recurring monthly costs that scale with active users, potential vendor lock-in, external network latency on every authentication check, and compliance hurdles if user credentials leave your jurisdiction.

Writing custom authentication in a Go backend is often surprisingly straightforward and dramatically more reliable for standard SaaS products. Go's standard library provides robust cryptographic primitives, fast HTTP routing, and clean concurrency. Storing sessions and users directly in your core PostgreSQL database keeps your domain logic unified, avoids distributed transactions, and ensures zero extra latency during request processing. When external systems need to trigger workflows or verify identities, you can protect endpoints using webhook security signatures.

For most B2B applications, starting with clean, custom Go authentication provides total architectural control, zero user-based subscription fees, and complete data privacy. When enterprise customers eventually require SAML/SSO integration, you can add an open-source identity bridge or integrate a specialized enterprise provider without rewriting your core session layer. If you are planning an end-to-end product architecture, explore our dedicated SaaS development service.

  • Adopt a managed provider: when you need turnkey SAML enterprise SSO on day one, lack backend engineering capacity, or build a fast consumer MVP.
  • Write custom Go authentication: when you want zero external SaaS dependencies, predictable infrastructure costs, sub-millisecond database lookups, and total control over data compliance.
  • Hybrid approach: manage core sessions and password credentials in your own Go database, while delegating complex enterprise SAML brokers to dedicated microservices.
Questions

FAQ

Didn't find an answer — ask on the call or in Telegram.

Session vs jwt authentication: which is better for a SaaS web application?

For a web SaaS application, server-side sessions stored in a database and passed via HttpOnly cookies are almost always the superior choice. Sessions provide instant token revocation, straightforward multi-device management, and complete immunity to JavaScript token theft. Stateless JWTs only make sense for high-scale, decoupled microservice APIs where central database lookups become an unacceptable performance bottleneck.

Where should tokens be stored in a web application?

Always store authentication tokens in HttpOnly, Secure cookies with the SameSite attribute set to Lax or Strict. This prevents browser JavaScript from accessing the token, fully mitigating exfiltration via cross-site scripting (XSS). Avoid LocalStorage and SessionStorage, because any injected script or vulnerable frontend dependency can instantly read credentials stored in Web Storage.

How do you securely hash passwords in Go?

Use the argon2id algorithm provided by the official golang.org/x/crypto/argon2 package. Argon2id provides memory-hardness and computational resistance against GPU cracking clusters. Generate a unique cryptographically secure 16-byte salt using crypto/rand for each password, store the salt and algorithm parameters alongside the hash, and verify incoming passwords using constant-time comparison to avoid timing attacks.

How does immediate session revocation work with JWT?

Pure stateless JWTs cannot be revoked before their expiration time without introducing server-side state. To revoke a JWT immediately, you must maintain a centralized blacklist of revoked token IDs (jti) in Redis or a database and check every incoming request against it. However, doing so eliminates the stateless benefit of JWTs, making opaque database sessions simpler and more efficient.

When should a SaaS write custom authentication in Go instead of using Auth0 or Clerk?

Write custom authentication in Go when you want full control over customer data, sub-millisecond session validation in your primary database, zero external network dependencies, and predictable hosting costs that do not scale per monthly active user. Choose managed providers like Clerk or Auth0 when you need complex enterprise SAML SSO out of the box and lack backend engineering resources.

How do you protect the login endpoint from brute force and credential stuffing?

Protect login endpoints by combining rate limiting on both client IP addresses and targeted account emails. Use Redis sliding window counters to throttle bursts and return HTTP 429 with exponential backoff. Enforce multi-factor authentication for sensitive accounts, log suspicious login locations, and use progressive delays rather than permanent account lockouts to prevent denial-of-service abuse.

Related service

Custom web services and SaaS platforms

A platform for customers or partners is more than an interface: behind it are accounts, permissions, payments and an API. We design those parts so the product can grow instead of being rewritten.

Learn about the service
Other articles
Contact

Shall we discuss your task?

Thirty minutes on a call — and you understand the architecture, timeline and engagement format. No obligations.

Or message us on Telegram →Follow our Telegram channel →

Enter your Telegram or email so we can reply.

We reply within 15 minutes.