Authentication In A Nutshell
Ever wonder how an app stores your password without exposing it to the people who built it?
They don't store your password. At all.
When you sign up, your password goes through something called a one-way hashing function. It spits out a scrambled string that can't be reversed back into your password. That string is what sits in the database.
For example, "sunshine123" gets stored as something like "$2b$10$N9qo8uLOickgx2ZMRZoMye". No way to work backwards from that string to your actual password.
When you log in, the app hashes what you typed and checks if it matches the stored hash. Match = you're in.
From there, the app hands you a JWT: a signed token that proves who you are. Every time you do something in the app, like load your feed, open a message, or update your profile, your device is quietly asking the server for that data. And that data has to be protected, because otherwise anyone could ask for it and read your stuff. Instead of sending your password with every single one of those asks, your device sends the token. Think of it like a wristband at a festival: you show your ID once at the gate, then the wristband gets you in everywhere else.
So even if a developer opens the database, or hackers steal it, all they see is gibberish. Nobody knows your password but you.
Here's the whole flow, start to finish:
- You enter your email and password.
- The app scrambles your password with the one-way hashing function.
- It checks the scrambled result against the scrambled string in the database.
- Match = you're logged in, and the app hands you a token (the wristband).
- Everything you do after that, your device shows the token instead of your password.
- Token expires, you log in again, new wristband.
For the technical folks, here's what's actually happening:
- User enters credentials into the login form.
- The client sends a POST request over HTTPS to the login endpoint (e.g. /api/login) with the credentials in the request body.
- The server (e.g. Express) queries the database for the user record by email.
- The server runs the submitted password through the hashing function (e.g. bcrypt) and compares it against the stored hash.
- On a match, the server signs a JWT containing the user's id and an expiry, using a secret key.
- The JWT is returned in the response and stored client-side (httpOnly cookie or localStorage).
- Every subsequent request includes the JWT in the Authorization header (Bearer <token>).
- Server middleware verifies the token's signature and expiry before the route handler runs.
- When the token expires, the client re-authenticates (or uses a refresh token) to get a new one.
Sources