Skip to content
Visual explainer 2h 30m to learn 4 steps

Authentication, authorization & password storage

Separate authentication from authorization and explain safe password storage.

By Invicly Tech, , in Cyber Security Fundamentals. About 10 minutes to read.

Topic 19 of 49

In short

Authentication proves who you are; authorization decides what you may do. Passwords must be stored as salted, slow hashes so a stolen database is hard to crack, which is why Argon2, scrypt and bcrypt replace plain or fast hashes.

Explained simply

Authentication answers "who are you?". You prove it with something like a password, a passkey or a fingerprint. Authorization answers "what are you allowed to do?". Logging in to a shop proves you are Maria; authorization decides that Maria can see her own orders but not other people's.

These are separate steps, and mixing them up causes real bugs. A system might check that you are logged in, but forget to check that the record you asked for is yours. That is an authorization failure, and it is one of the most common web security problems.

Passwords need special care when stored. A site should never keep the actual password. It keeps a hash made with a slow, salted function. Then, if the database is stolen, attackers still have to guess each password one by one, slowly.

Attackers also reuse passwords leaked from other sites. This is called credential stuffing. Defences include multi-factor authentication, blocking known-leaked passwords, and spotting many failed logins across many accounts.

Press Play on a diagram to walk through it one step at a time.

FlowLogin then access
  1. Step 1
    Authenticate

    Verify identity with credentials.

  2. Step 2
    Issue token/session

    Represent the proven identity.

  3. Step 3
    Authorize

    Check permissions per request.

  4. Step 4
    Allow or deny

    Based on the user's rights.

MapWhere identity checks live in a web app
Incoming request
  • Authentication
    • Login: password, passkey, MFA
    • Session cookie or token check
    • Fails: 401
  • Authorization
    • Role or permission check
    • Ownership check on the record
    • Fails: 403 or 404
  • Credential storage
    • Argon2id hash + salt
    • Optional pepper in a secrets store
  • Abuse controls
    • Rate limits
    • Breached password check
    • Login anomaly alerts

In depth

Authentication, sessions and authorization on every request

Authentication usually happens once, at login. After that, the server gives the client a session cookie or a token that stands for the proven identity. Authorization must happen on every request, on the server, for every resource: "may user 42 read invoice 9001?".

HTTP status codes reflect the difference. 401 Unauthorized, despite its name, means "not authenticated": no valid credentials were sent. 403 Forbidden means "authenticated, but not allowed". Some apps return 404 instead of 403 so attackers cannot even learn that a record exists.

Good design puts authorization in one central place, such as middleware or a policy function, and denies by default. If every endpoint writes its own checks, one will eventually be forgotten. Log authorization failures: a user getting many 403s in a row is often probing other people's records.

  • 401: who are you? 403: I know you, and no
  • Check authorization server-side on every request
  • Deny by default; allow only what a rule permits

Why password hashes must be salted and slow

If a site stores plain passwords, one breach exposes every account. If it stores a fast hash like SHA-256, attackers can test billions of guesses per second on a single GPU, and common passwords fall in seconds. Precomputed tables (rainbow tables) make unsalted hashes even easier.

A salt is a random value, unique per user, stored next to the hash and mixed in before hashing. It means two users with the same password get different hashes, and precomputed tables become useless. A salt is not secret.

A slow, purpose-built password hash then makes each guess expensive. These functions have a cost setting you can raise as hardware gets faster. Some systems add a pepper: one extra secret mixed in, stored outside the database (for example in a secrets manager), so a database-only leak is not enough to start cracking.

On successful login, check whether the stored hash uses old settings and re-hash it with the new ones.

FlowChecking a password at login
  1. 1
    User sends password

    Over TLS only

  2. 2
    Load stored record

    Algorithm, cost, salt, hash

  3. 3
    Hash the attempt

    Same algorithm, cost and salt

  4. 4
    Compare in constant time

    Match: log in; no match: generic error

  5. 5
    Upgrade if needed

    Re-hash with current cost

bcrypt, scrypt and Argon2 compared

All three are designed for passwords, but they differ. bcrypt (1999) has a cost factor where each +1 doubles the work. It uses little memory, so GPUs can attack it somewhat efficiently, and it only uses the first 72 bytes of a password. scrypt adds a memory cost, which makes GPU and custom-hardware attacks much more expensive. Argon2 won the Password Hashing Competition in 2015; Argon2id is the variant to use.

OWASP's current guidance: Argon2id with at least 19 MiB of memory, 2 iterations and 1 degree of parallelism. If Argon2id is not available, use scrypt (N=2^17, r=8, p=1), then bcrypt with cost 10 or more. Where FIPS compliance is required, PBKDF2-HMAC-SHA256 with 600,000 iterations.

Tune for your hardware: a login should take somewhere around tens to a few hundred milliseconds. Too slow, and attackers can overload your login endpoint.

ComparePassword hashing choices
Argon2id
  • First choice today
  • Memory-hard
  • m=19 MiB, t=2, p=1 minimum
  • Format starts $argon2id$
scrypt
  • Good second choice
  • Memory-hard
  • N=2^17, r=8, p=1
  • Common in older systems
bcrypt
  • Still acceptable
  • Cost 10 or higher
  • Only first 72 bytes used
  • Format starts $2b$

Defending against credential stuffing

Billions of username and password pairs from old breaches are traded online. Attackers feed them into automated tools that try each pair on your login page, often through thousands of residential proxy IPs so each IP sends only a few requests. Because people reuse passwords, a small share of attempts succeed.

Layered defences work best. MFA stops a correct password from being enough. Checking new passwords against breach lists, for example with the Have I Been Pwned Pwned Passwords API, blocks known-leaked choices; NIST's SP 800-63B guidance also says to allow long passphrases and drop forced periodic changes and odd composition rules. Rate limit by account and by IP, and add bot detection or a challenge when traffic looks automated.

For detection, watch the overall login failure rate, many accounts failing from many IPs in a short window, and success from an IP that also failed against hundreds of other accounts. Use the same error message for wrong user and wrong password.

  • Signal: failure rate jumps across the whole site
  • Signal: one IP or ASN tries many different usernames
  • Response: force password reset and MFA for accounts that logged in

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Separate authentication from authorization~40m
  2. 2
    Explain salted slow password hashing~40m
  3. 3
    Compare bcrypt, scrypt and Argon2~40m
  4. 4
    Explain credential stuffing defences~40m

Key points

  • Authentication and authorization are separate steps.
  • Never store passwords in plain text or fast hashes.
  • Salt makes identical passwords hash differently.
  • Slow hashes like Argon2 resist mass cracking.

Key terms

Tap a card to flip it. 0/4 known

Examples

Storing passwords with Argon2id in Python

Step 1: install argon2-cffi. Step 2: create a PasswordHasher; its defaults use Argon2id with 64 MiB memory, 3 iterations and 4 lanes, above OWASP's minimum. Step 3: hash at sign-up; the output string holds the algorithm, settings, salt and hash, so you store just that one field. Step 4: at login, verify raises an exception on a wrong password. Step 5: check_needs_rehash tells you when to upgrade an old hash to new settings.

python
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher()
stored = ph.hash("correct horse battery staple")
print(stored)   # $argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash>
def login(password: str) -> bool:
    try:
        ph.verify(stored, password)
    except VerifyMismatchError:
        return False
    if ph.check_needs_rehash(stored):
        pass  # save ph.hash(password) as the new stored value
    return True
print(login("correct horse battery staple"), login("guess123"))

Blocking breached passwords without sending them anywhere

The Pwned Passwords API uses k-anonymity. Step 1: hash the candidate password with SHA-1 (used here only as a lookup key, not for storage). Step 2: send only the first 5 hex characters. Step 3: the API returns every suffix that starts with that prefix, with a count. Step 4: check locally whether your full suffix is in the list. The service never sees the password or even its full hash. Step 5: if the count is above zero, ask the user to choose another password.

python
import hashlib, urllib.request
def pwned_count(password: str) -> int:
    h = hashlib.sha1(password.encode()).hexdigest().upper()
    prefix, suffix = h[:5], h[5:]
    req = urllib.request.Request(
        f"https://api.pwnedpasswords.com/range/{prefix}",
        headers={"User-Agent": "password-check-demo"})
    with urllib.request.urlopen(req) as r:
        for line in r.read().decode().splitlines():
            s, count = line.split(":")
            if s == suffix:
                return int(count)
    return 0
print(pwned_count("password123"))   # a large number

Quick reference

  • Authentication = who you are; authorization = what you may do, checked on every request
  • 401 means not authenticated; 403 means authenticated but not allowed
  • Store passwords with Argon2id (OWASP min: 19 MiB, t=2, p=1); never plain or SHA-256
  • Salts are unique per user and not secret; a pepper is secret and kept outside the DB
  • bcrypt ignores bytes after 72; use cost 10 or more
  • Same error for wrong user and wrong password stops username discovery
  • Credential stuffing signal: many accounts failing from many IPs at once
  • Pwned Passwords range API: send only the first 5 SHA-1 hex characters

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A logged-in user changes /orders/1001 to /orders/1002 in the URL and sees someone else's order. Which control failed?

Question 2

2What does a per-user salt mainly defeat?

Question 3

3Which password hashing choice does OWASP list first?

Question 4

4Your login page sees 50,000 failed logins in 10 minutes, each IP trying only 2 or 3 different usernames. What is this most likely?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Hash the same password twice with bcrypt and show the results differ. Then show both still verify.

  2. Exercise 2medium

    Measure how long one Argon2id hash takes on your machine with OWASP's minimum settings and with argon2-cffi's defaults. Pick settings that take about 100 to 300 ms.

  3. Exercise 3hard

    Write a log analysis that flags credential stuffing: from a CSV of login attempts (time, ip, username, success), find IPs that tried 20 or more distinct usernames, and list any successful logins from those IPs.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should passwords be encrypted or hashed?
Hashed with a slow password hash. Encryption can be reversed by anyone who gets the key, and the server never needs to know the original password, only to check a guess.
Should I force users to change passwords every 90 days?
Current NIST guidance says no, unless there is evidence of compromise. Forced changes lead to weak, predictable passwords; check against breach lists and use MFA instead.
Is it safe to tell users "this username does not exist"?
It lets attackers find valid accounts. Use one generic message such as "wrong username or password", and the same for password reset requests.
What is the difference between a salt and a pepper?
A salt is random per user and stored with the hash. A pepper is one secret value for the whole system, stored separately, so a stolen database alone is not enough to crack hashes.

Go deeper

ShareXLinkedInWhatsApp