Skip to main content
Secure Authentication and Session Best Practices

Secure Authentication and Session Best Practices

KU
· Founder & Chief Editor
• 8 min read•Updated •46 views

A practical guide to hashing passwords, adding MFA, hardening sessions, and avoiding the JWT mistakes that break production auth.

Key takeaways

  • Hash passwords with argon2id, offer passkeys as the strong second factor, and keep sessions server-side in HttpOnly, Secure, SameSite cookies that rotate on login and die on logout.
  • Treat JWTs as short-lived tokens with a pinned algorithm and checked exp, aud and iss claims, and rate-limit every login endpoint.

Secure authentication comes down to five choices: hash passwords with argon2id, make passkeys the strong second factor, keep sessions server-side in HttpOnly, Secure, SameSite cookies that rotate on login, treat JWTs as short-lived and fully verified, and rate-limit every login endpoint. None of it is novel. The breaches come from skipping one.

Verified against

argon2-cffi 25.1.0, PyJWT stable docs, against the OWASP Password Storage and Session Management cheat sheets and RFC 8725 (JWT Best Current Practices). Checked October 2026.

Authentication is where most breaches start, and where teams cut the most corners. The correct approach is well understood and mostly means picking the right primitives and refusing to be clever. This post covers password storage, MFA, session management, and the JWT traps that keep showing up in incident reports. It sits alongside our broader application security best practices guide.

Store passwords the boring, correct way

If you take one thing away: use a purpose-built password hashing function, not a general-purpose digest. MD5 and SHA-1 are fast, and fast is exactly wrong for passwords because it lets an attacker try billions of guesses per second against a stolen table.

Reach for argon2id first. It is memory-hard, which blunts GPU and ASIC cracking rigs, and it is OWASP's first recommendation; the Password Storage Cheat Sheet's minimum is 19 MiB of memory, 2 iterations, parallelism 1 (as of October 2026). scrypt is OWASP's next choice, and bcrypt is now listed for legacy systems where neither is available: use a work factor of at least 10 and cap passwords at 72 bytes, because most bcrypt implementations silently truncate beyond that. Both algorithms generate a per-user salt automatically and encode it into the output string, so you do not manage salts yourself.

Python
# auth/passwords.py
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

# These equal argon2-cffi's defaults (RFC 9106 low-memory profile: 64 MiB, t=3, p=4),
# well above OWASP's 19 MiB / t=2 / p=1 floor. Tune memory_cost to your hardware.
ph = PasswordHasher(time_cost=3, memory_cost=64 * 1024, parallelism=4)

def hash_password(plaintext: str) -> str:
    return ph.hash(plaintext)  # returns full encoded string incl. salt + params

def verify_password(stored_hash: str, plaintext: str) -> bool:
    try:
        ph.verify(stored_hash, plaintext)
    except VerifyMismatchError:
        return False
    # Transparently upgrade if you have raised the cost parameters.
    if ph.check_needs_rehash(stored_hash):
        # re-hash and persist the new value on successful login
        pass
    return True

Peppering, a secret value mixed in before hashing and kept outside the database (in a KMS or app config), is an optional extra layer. It helps only if your database leaks but your secret store does not, and it adds operational cost around rotation. Treat it as defense in depth, not a substitute for a strong algorithm.

One rule underlies all of this: do not roll your own crypto. Use a maintained library binding, keep it updated, and let the algorithm do the salting.

Make MFA the norm, and make it strong

A password alone is a single point of failure. Adding a second factor blunts phishing, credential stuffing, and reuse.

TOTP (the six-digit codes from an authenticator app) is a solid baseline and easy to implement with any RFC 6238 library. It is far better than SMS, which is vulnerable to SIM swapping and interception.

The strong option is WebAuthn / passkeys. Because the credential is bound to your origin and the private key never leaves the authenticator, passkeys are phishing-resistant by design: a lookalike domain simply cannot produce a valid assertion. If you are building auth today, plan for passkeys as a first-class path rather than an afterthought.

Sessions: server-side, and cookies done right

Once a user authenticates, you need to remember them. Prefer opaque, server-side session identifiers stored in a fast store (Redis, a database) with the ID handed to the client in a cookie. The cookie should carry:

  • HttpOnly: blocks JavaScript from reading the cookie, so XSS cannot exfiltrate the session.
  • Secure: the cookie is only sent over HTTPS.
  • SameSite=Strict or Lax: limits cross-site sending, cutting off a class of CSRF. OWASP prefers Strict; Lax is the usual compromise when users arrive from links. Pair this with proper CSRF protection for state-changing requests.
Python
# auth/session.py
response.set_cookie(
    "session",
    session_id,
    httponly=True,
    secure=True,
    samesite="Lax",
    max_age=60 * 60 * 8,   # absolute cap
    path="/",
)

Beyond flags, three behaviors matter:

Rotate the session ID on login. Issue a fresh identifier the moment a user authenticates and discard any pre-login ID. This closes session fixation, where an attacker plants a known session ID and waits for the victim to log in with it.

Enforce two timeouts. An idle timeout expires sessions after a period of inactivity; an absolute timeout caps total lifetime regardless of activity. Both should be enforced server-side, not merely by cookie expiry, which the client controls.

Actually invalidate on logout. Logout must delete the session record on the server, not just clear the cookie. If the record survives, a captured ID stays valid.

JWT: powerful, and easy to misuse

JSON Web Tokens are useful for stateless service-to-service claims, but they are a frequent source of authentication bugs. The recurring mistakes:

  • The alg: none trap. Some libraries once honored a header claiming no signature, letting anyone forge a token. RFC 8725 requires libraries to let callers pin the accepted algorithms; always pass that list server-side and reject anything else.
  • Weak or shared secrets. An HMAC key you can guess is a skeleton key. Use a long random secret, or asymmetric keys (RS256/ES256) so verifiers never hold signing material.
  • Not verifying the whole token. Verifying the signature is necessary but not sufficient. You must also check exp (expiry), aud (audience), and iss (issuer). A valid signature on a token minted for a different service is still the wrong token. In PyJWT, options={"require": [...]} only checks the claims exist; audience and issuer check their values.
  • Storing JWTs in localStorage. This exposes the token to any XSS on the page. Prefer an HttpOnly cookie, or keep access tokens short-lived and in memory only.
  • Revocation is genuinely hard. A signed token is valid until it expires; there is no natural "log this token out." Keep access-token lifetimes short (minutes), use refresh tokens you can revoke server-side, and maintain a denylist if you need immediate cutoff.
Python
# auth/tokens.py
import jwt  # PyJWT

def verify_token(token: str, secret: str) -> dict:
    return jwt.decode(
        token,
        secret,
        algorithms=["HS256"],          # pin it; never trust the header's alg
        audience="api.example.com",    # verify aud
        issuer="auth.example.com",     # verify iss
        options={"require": ["exp", "aud", "iss"]},
    )

Slow down the guessers

Online guessing attacks are cheap to run and cheap to defend against. Apply rate limiting per account and per IP on login and MFA endpoints. Add progressive delays or a temporary account lockout after repeated failures, tuned so you frustrate attackers without letting them lock out real users on purpose. For credential stuffing, where attackers replay passwords leaked elsewhere, check submitted passwords against a breached-password corpus and lean on MFA to make valid credentials insufficient on their own.

Password reset and error messages

Reset flows are a common bypass. Generate a high-entropy, single-use token, store only its hash, give it a short expiry, and invalidate it once used or once a new one is requested. Never email the password or a reversible token.

Finally, keep responses generic. "Invalid username or password" beats "no such user," and a reset endpoint should say "if that address exists, we sent a link" regardless of outcome. Distinct responses hand attackers a user-enumeration oracle. Keep timing consistent too, so response latency does not leak the same information.

Questions people ask

What is the best password hashing algorithm in 2026?

Argon2id. The OWASP Password Storage Cheat Sheet lists it first, with a minimum of 19 MiB of memory, 2 iterations and parallelism 1 as of October 2026. Use scrypt if Argon2 is unavailable, PBKDF2 with 600,000 HMAC-SHA-256 iterations when FIPS-140 compliance is required, and bcrypt only on legacy systems. Never use plain MD5, SHA-1 or SHA-256 for passwords.

A cookie with HttpOnly, Secure and SameSite set. Anything in localStorage is readable by every script on the page, so a single XSS bug hands over the token. An HttpOnly cookie cannot be read by JavaScript at all. Pair the cookie with CSRF protection for state-changing requests, and keep access tokens short-lived so a stolen one expires quickly.

How long should a user session last?

OWASP's Session Management Cheat Sheet suggests an idle timeout of about 2 to 5 minutes for high-value applications and 15 to 30 minutes for low-risk ones, enforced on the server. Add an absolute timeout as well; its example is 4 to 8 hours for someone using an app through a workday. Rotate the session ID at login and delete the server record at logout.

The call we'd make

Use argon2id for passwords, make passkeys your strong MFA path, and keep sessions server-side with HttpOnly, Secure, SameSite cookies that rotate on login. Treat JWTs as short-lived, fully-verified claims with pinned algorithms, never as long-lived credentials in localStorage. And wrap it all in rate limiting and generic errors. None of this is novel, which is the point: authentication rewards discipline over cleverness.

Sources

Explore topics:SecurityDevOps
React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). Secure Authentication and Session Best Practices. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/secure-authentication-best-practices

Markdown

[Secure Authentication and Session Best Practices](https://www.devopsness.com/blog/secure-authentication-best-practices) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

586 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.