Skip to content

Password storage and sessions

How a service keeps passwords it can check but not read (a slow, salted hash) and how it remembers a logged-in user afterward (a random session ID in a locked-down cookie, or a signed token).

On this page

What it is

Password storage is the part of a design that lets a service check a password without being able to read it back. The service runs the password through a deliberately slow, salted hash function and keeps the output; at login it repeats the computation and compares. Hashing is one-way, so a leaked table of hashes doesn't hand an attacker a list of passwords, and the attacker is left guessing candidates one at a time. Encryption is the wrong tool here because it can be reversed by anyone holding the key; the rare exception is a system that must forward the password to another system that offers no modern delegated login.

Three settings make a stored hash hard to crack. The salt is a random value unique to each user, stored next to the hash, so an attacker can't precompute a table or spot two users with the same password; modern password hashing functions require one, and most libraries generate and store it for you. The work factor (cost) sets how much CPU and, for memory-hard functions, how much RAM each hash takes, which raises the price of each guess an attacker makes. It can be raised later as hardware gets cheaper, usually by re-hashing when the user next logs in, which works because the cost is normally recorded in the hash output itself. A pepper is a secret shared across all hashes and kept outside the database, in a secrets vault or HSM, so a stolen database dump on its own isn't crackable; rotating it means forcing resets, since you can't recompute a hash without the password.

AlgorithmFloor OWASP givesWhen it's the right pick

Argon2id

19 MiB memory, 2 iterations, parallelism 1

New systems; memory-hard, so GPU farms gain less

scrypt

Cost 2^17, block size 8, parallelism 1

Argon2id isn't available in your stack

bcrypt

Work factor 10 or more; input capped at 72 bytes

Existing systems already on it

PBKDF2-HMAC-SHA-256

600,000 iterations or more

FIPS-140 compliance is required

MD5, SHA-1, plain SHA-256

None: built to be fast

Not for passwords; migrate on next login

A session is how the service recognizes the same user across later requests, since HTTP carries nothing between them. After login the server issues a session ID, which from then on is as good as the password itself. The ID should be a random value with at least 64 bits of entropy from a cryptographically secure generator, carry no meaning of its own (no user ID, role or email inside it), and point to a record the server keeps: who the user is, when the session was created, when it was last used. OWASP's worked example: at 64 bits, an attacker trying 10,000 guesses a second against 100,000 live sessions would need on the order of 585 years to hit one.

The ID travels in a cookie, and the cookie's attributes decide who can read it. Secure makes the browser send it on HTTPS requests and withhold it from plain HTTP, with an exception for localhost. HttpOnly blocks page scripts from reading it through document.cookie, so a cross-site scripting bug can't copy the session out; the browser still attaches the cookie to requests that scripts make, so such a bug can still act inside the session. SameSite=Strict withholds the cookie from cross-site requests; SameSite=Lax also sends it on top-level navigations with a safe method, such as a link click from another site; SameSite=None sends it everywhere and requires Secure. A __Host- prefix on the name asks the browser to reject the cookie unless it is Secure, has no Domain attribute and uses Path=/, which keeps a subdomain from setting it.

http
HTTP/1.1 200 OK
Set-Cookie: __Host-sid=4f9c0a7d3e21b8c6d5a4f3e2c1b0a9f8; Secure; HttpOnly; SameSite=Lax; Path=/

The alternative to a server-side record is a signed token such as a JWT: the server puts the user's claims and an expiry in the token, signs it, and later verifies the signature instead of looking anything up. That removes the shared store, but it also removes the place where a session gets canceled. Logging a user out before the token expires needs a deny list of revoked tokens that each verifier checks, and once that exists the design is no longer stateless. Short expiries bound how long a stolen or revoked token stays usable.

When to use it

Any time your design has a login box, say where the password hash lives and how the session is carried. The password table is the part that is still dangerous after a breach, so a strong answer names the algorithm and its cost up front, keeps a hash computation under about a second on your servers so login latency and a flood of login attempts don't become a denial of service, and plans the upgrade path: keep the algorithm and cost readable from each record and re-hash at the next successful login when you raise them.

Pick an opaque session ID with a server-side store for a browser product where you need logout, "sign out everywhere" and password changes to take effect at once; the store is a lookup per request, usually a cache such as Redis or a table keyed by the ID. Regenerate the ID at login and at any privilege change (a role switch, a password change), so an ID an attacker planted before login is worthless afterward; this is the defense against session fixation. Give each session an idle timeout and an absolute timeout checked on the server, and have logout delete the record, because clearing the cookie doesn't invalidate a copy an attacker already has. For an application used through an office day, guidance from OWASP puts the absolute timeout in the range of 4 to 8 hours.

Pick a signed token when many services must authenticate a request without a round trip to a shared store: give it a short lifetime, an audience and an issuer, and a token ID (jti) so that a deny list keyed on it is possible for the rare revocation. We'd pair it with a longer-lived refresh credential that is itself revocable, so the short token can be minted again without a new login. A mobile app or another service can carry an opaque ID in a header just as well as a signed token, so the client's type on its own doesn't decide this. Our view: for a single web app with one backend, the opaque session is simpler and gives you revocation for free; reach for tokens when the topology demands it.

When not to

Don't hash with a general-purpose function such as SHA-256 or MD5, even salted: they are built to be fast, which is the property an attacker with GPUs wants. Don't treat a pepper as a substitute for a slow hash; on its own it adds no security. And don't tune the work factor as high as it goes: a hash that takes several seconds makes each login slow and lets an attacker exhaust your CPU with a stream of login attempts.

Don't write your own session ID generator when your framework has one; if you must, use a cryptographically secure generator with at least 128 bits. Don't accept the session ID from a URL parameter or a hidden form field when it should arrive in a cookie; refusing other channels is part of the defense against fixation. And don't rely on the cookie's own expiry, or on the browser closing, to end a session: browsers restore session cookies, and a client-held timer can be edited by the client. The server's record is where expiry is enforced.

Don't choose a stateless JWT for a product where logout, a password change or an admin ban must stop access right now. The deny list you'd add to get that back is state again, and keying it on a hash of the raw token is unsafe because an attacker can re-encode a revoked token into another form that still verifies. Key the list on the token's own ID instead, or keep the plain server-side session.

When a password can be skipped it's the strongest storage choice of all: a single sign-on or OpenID Connect login against an identity provider means your service holds no password hashes to breach. Our advice: in a design round, say so when the product allows it, and keep the hashing answer for the case where users do set a password with you.

Compared

ChoiceStronger optionWeaker option is right when

Hash function

Argon2id: memory-hard, resists GPU and side-channel attacks

bcrypt on a legacy stack with cost 10+; PBKDF2-HMAC-SHA-256 at 600,000+ rounds when FIPS-140 is a requirement

Where session state lives

Opaque ID plus a server-side record: instant revocation, nothing sensitive in the cookie

A signed token when many services must verify requests without a shared store, and a short expiry is an acceptable revocation delay

SameSite value

Strict: the cookie is withheld from cross-site requests

Lax, so a link from an email or another site opens the user already signed in; keep a CSRF token either way

Timeout

Absolute timeout plus idle timeout, enforced server-side

A longer absolute timeout with a renewal timeout that rotates the ID mid-session, for products that must stay signed in for days

Extra defense

A pepper kept in a secrets vault or HSM

No pepper when you can't operate a separate secret safely; rotating it forces resets for all users

In a picture

Sign-up formArgon2id with saltand costUsers table

Step 1 of 4

Sign-up: hash and store

The service generates a random salt, runs Argon2id over the password with the current cost, and stores one record holding the algorithm, the cost, the salt and the hash. The password itself is discarded.

How to say it in an interview

The common mistake

Quiz

A teammate proposes storing passwords as salted SHA-256. What's the problem?
Why does a session ID need to be regenerated at the moment a user logs in?
Sessions are stateless JWTs with a 24-hour expiry. A user clicks "sign out of all devices". What does the service need?
Hardware got cheaper and you want to raise the hashing cost for existing users. What's the usual approach?

Related

Sources

  1. OWASP: Password Storage guidance
  2. OWASP: Session Management guidance
  3. OWASP: JSON Web Token guidance
  4. MDN: Set-Cookie header
Sign in to report a mistake