← Tous les articles

SaaS authentication: sessions or JWTs? Picking the right one (and the traps in each)

Server-side sessions or JWTs to sign users into your SaaS app? What each approach actually does, the revocation problem, where the token should live, and the default we use on our own projects.

SaaS authentication: sessions or JWTs? Picking the right one (and the traps in each)

Key points

  • For a web app served from its own domain, a session in an HttpOnly cookie is still the simplest and safest option.
  • The real weak spot of JWTs is revocation: forced sign-out, password changes, users removed from an organisation.
  • Tokens make sense for a public API, a mobile app or service-to-service calls, with short lifetimes.

It’s a decision made in the first week of a SaaS project and it’s painful to undo later: how does the server know, on every request, who the user is? Plenty of recent tutorials go straight to JWTs stored in the browser and present them as the modern way. On the apps we build and inherit, what we mostly see are the side effects of that default: sign-outs you can’t enforce, stolen tokens that keep working, and a refresh layer that ends up rebuilding server-side sessions anyway. Here’s how to decide.

What each approach really does

A session is a random, meaningless ID sent in a cookie. The server keeps the associated data (the user, their organisation, when they signed in) in a store: files, a database or Redis. On every request it looks the session up by ID. Delete the session on the server and the user is signed out, instantly.

A JWT (JSON Web Token) carries the data itself and is signed by the server. Validating it only takes checking the signature and the expiry, with no database lookup. That’s its big selling point when several services need to authenticate a request without sharing storage.

A common misunderstanding: a JWT is signed, not encrypted. Anyone who gets hold of one can read it in three lines:

// A JWT payload isn't encrypted: anyone can read it
const [, payload] = token.split('.');
const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
console.log(JSON.parse(json));
// { "sub": "42", "tenant": "acme", "role": "admin", "exp": 1763481600 }

So never put anything sensitive in it, and treat it like a temporary password: whoever holds it is that user until it expires.

The part tutorials skip: revocation

In a SaaS there are plenty of moments when access has to stop now, not in an hour:

  • the user hits “Sign out of all devices” after losing their phone;
  • they change their password because they think it leaked;
  • a customer admin removes someone who has left the company;
  • the subscription is suspended, or admin rights are taken away;
  • your team spots suspicious activity on an account.

With sessions this is trivial: delete or invalidate the session. With a JWT, the token stays valid until it expires, because nothing checks it beyond its signature. Every standard fix brings server state back: a deny-list of revoked tokens checked on each request, or very short-lived access tokens (a few minutes) paired with a refresh token stored in the database that you can revoke.

That second design is sound, but it isn’t free: two kinds of token, refresh-token rotation, reuse detection, and handling parallel requests that all try to refresh at once. For a regular web app, that’s a lot of moving parts to get back what a session gives you out of the box.

Where the token lives in the browser

This is the second sticking point. A JWT kept in localStorage can be read by any JavaScript on the page. A single XSS bug, or a compromised third-party script (analytics, a support widget), is enough to ship it elsewhere, and the attacker can then use it from their own machine.

A cookie flagged HttpOnly can’t be read by JavaScript. An XSS bug is still serious, but it can’t lift the session ID for use elsewhere. SameSite=Lax also stops the cookie being sent on form posts from other sites, which covers most CSRF risk (a CSRF token is still a good idea for sensitive actions).

This is the session setup we use in PHP:

<?php
// Before session_start(): a hardened session cookie
ini_set('session.use_strict_mode', '1');   // reject made-up session IDs
session_set_cookie_params([
    'lifetime' => 0,          // browser-session cookie (expiry handled server-side)
    'path'     => '/',
    'secure'   => true,       // HTTPS only
    'httponly' => true,       // not readable from JavaScript
    'samesite' => 'Lax',      // not sent by other sites' form posts
]);
session_start();

// After a successful login
session_regenerate_id(true);  // new ID: prevents session fixation
$_SESSION['user_id']         = $user->id;
$_SESSION['tenant_id']       = $user->tenantId;
$_SESSION['session_version'] = $user->sessionVersion;

On the JavaScript side there’s nothing to do: the browser sends the cookie automatically with fetch() to the same origin. If your API sits on a separate subdomain, you’ll need credentials: 'include' in the client and Access-Control-Allow-Credentials on the server, with an explicit origin rather than *.

You can also put a JWT in an HttpOnly cookie. That solves storage, but not revocation.

Clean revocation with sessions

To cover every case in the list above without trawling the session store, we add a session_version column to the users table. It’s copied into the session at login and compared on every request:

<?php
// On every authenticated request: is this session still valid?
$stmt = $pdo->prepare('SELECT session_version, is_active FROM users WHERE id = ?');
$stmt->execute([$_SESSION['user_id']]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row || !$row['is_active']
    || (int) $row['session_version'] !== $_SESSION['session_version']) {
    $_SESSION = [];
    session_destroy();
    header('Location: /login');
    exit;
}

// "Sign out of all devices", password change,
// user removed from the organisation: one query does it
// UPDATE users SET session_version = session_version + 1 WHERE id = ?

It’s one extra primary-key lookup per request; on our projects it doesn’t register, and it doubles as a check that the account is still active. If you already load the user on every request, as most frameworks do, it costs nothing.

To spread load across several servers, store sessions in Redis or the database instead of local files. That takes care of the “sessions don’t scale” argument with a line of config.

Our default, and when tokens make sense

On the SaaS products we build, the rule is:

  • Web app served from your own domain: sessions in an HttpOnly, Secure, SameSite=Lax cookie. That’s the vast majority of SaaS dashboards.
  • API for your customers (integrations, scripts): long API keys, stored hashed and revocable, rather than JWTs.
  • Mobile app: short access tokens plus a refresh token kept in the device’s secure keychain and revocable on the server.
  • Calls between your own services: this is where a short-lived JWT, with issuer, audience and algorithm all checked, is a great fit.

If you do use JWTs, always validate them with an algorithm the server chooses, and check issuer and audience. With the firebase/php-jwt library:

<?php
use FirebaseJWTJWT;
use FirebaseJWTKey;

JWT::$leeway = 30; // allow 30 s of clock skew

// The server decides the algorithm; never trust the token's header
$claims = JWT::decode($token, new Key($publicKey, 'RS256'));

if ($claims->iss !== 'https://auth.mysaas.com' || $claims->aud !== 'api') {
    throw new RuntimeException('Token not meant for this service');
}
// decode() checks exp and nbf and throws if they fail

Pinning the algorithm server-side isn’t pedantry: several well-known vulnerabilities came from libraries that trusted whatever algorithm the token’s header claimed.

FAQ

Are JWTs less secure than sessions?

Not inherently: the signature is solid. The trouble comes from how they’re usually deployed, in localStorage with long lifetimes and no way to revoke them. Done properly, short-lived with a revocable refresh token, they’re secure, just more complex.

Do sessions work across multiple servers?

Yes, as long as sessions live in shared storage such as Redis or the database rather than in local files on each server.

Do I still need a CSRF token with SameSite=Lax?

For sensitive actions, yes. SameSite=Lax blocks most cross-site form attacks, but it won’t save you from a GET request that changes data, or from an attack launched from a compromised subdomain.

Launching a SaaS, or need to rework authentication in an existing app? We design and audit authentication setups that are secure and easy to maintain.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →