Lesson 7 of 16
Authentication & sessions
Most real apps need to know who a user is — to show their data, protect private pages, personalize. Authentication ("are you who you say you are?") and sessions (staying logged in across requests) are how. This is a critical, security-sensitive part of the back-end. Let's understand how login and staying-logged-in work.
Authentication vs authorization
Two related but distinct concepts:
- Authentication — verifying who you are (logging in with credentials). "Are you really Ada?"
- Authorization — determining what you're allowed to do once identified. "Is Ada allowed to delete this?"
This lesson is about authentication (login); authorization (permissions) comes next. First a user proves their identity (authentication), then the app decides what they can access (authorization).
The login flow
// A login route: verify credentials, then start a session
app.post("/api/login", async function (req, res) {
const { email, password } = req.body;
// 1. Find the user by email:
const user = await db.query("SELECT * FROM users WHERE email = ?", [email]);
if (!user) {
return res.status(401).json({ error: "Invalid credentials" });
}
// 2. Check the password (against a HASH - next lesson):
const valid = await checkPassword(password, user.passwordHash);
if (!valid) {
return res.status(401).json({ error: "Invalid credentials" });
}
// 3. Log them in (start a session / issue a token - below):
// ...
res.json({ success: true });
});
Logging in: the user submits credentials (email + password); the server finds the user, verifies the password (against a stored hash, never plain text — next lesson), and if valid, establishes that they're logged in. If the credentials are wrong, return 401 Unauthorized (with a generic message — don't reveal whether the email or password was wrong, to avoid helping attackers). This is the core authentication flow.
The problem: HTTP is stateless
Here's the challenge: HTTP is stateless — each request is independent, with no memory of previous ones. So after a user logs in, the next request doesn't inherently "know" they're logged in. We need a way to remember them across requests. Two common approaches:
- Sessions (with cookies) — the server stores session data and gives the browser a cookie.
- Tokens (like JWT) — the server issues a signed token the client sends with each request.
Both solve the same problem: proving on each subsequent request that "this is the user who logged in."
Sessions with cookies
// SESSION approach: server remembers the logged-in user, browser holds a cookie
app.post("/api/login", async function (req, res) {
// ...after verifying credentials...
req.session.userId = user.id; // store who's logged in, server-side
res.json({ success: true });
// The browser automatically gets a session cookie and sends it on every request.
});
// A later request can check the session:
app.get("/api/profile", function (req, res) {
if (!req.session.userId) {
return res.status(401).json({ error: "Not logged in" });
}
// ...return the logged-in user's profile...
});
With sessions: on login, the server stores the user's identity (server-side) and sends the browser a session cookie. The browser automatically includes that cookie on every subsequent request, so the server can look up "who is this?" and know they're logged in. To log out, you destroy the session. Sessions are a classic, solid approach, especially for traditional web apps.
Tokens (JWT)
// TOKEN approach (JWT): server issues a signed token; client sends it each time
app.post("/api/login", async function (req, res) {
// ...after verifying credentials...
const token = createToken({ userId: user.id }); // a signed JWT
res.json({ token: token }); // client stores it and sends it on future requests
});
// Later requests include the token (usually in an Authorization header),
// and the server verifies it to identify the user.
With tokens (commonly JWT — JSON Web Tokens): on login, the server issues a signed token containing the user's id. The client stores it and sends it with each request (typically in an Authorization header); the server verifies the token's signature to trust it. Tokens are popular for APIs and single-page apps (like React front-ends). Both sessions and tokens are valid — the choice depends on your app; understand that both maintain login state across stateless requests.
The mistake beginners make
Building authentication carelessly — it's security-critical and easy to get dangerously wrong. Common mistakes: storing passwords in plain text (never — hash them, next lesson), revealing which part of the credentials was wrong (help attackers), not using HTTPS (credentials sent in the clear), or rolling your own crypto. Strongly prefer well-tested authentication libraries/services rather than building it from scratch. Also, confusing authentication (who you are) with authorization (what you can do). Understand the concepts, use proven tools, and treat auth as the sensitive area it is.
Your turn
// Outline a "check if logged in" middleware and a protected route:
// - a function that checks the session (or token) for a logged-in user
// - if not logged in, respond 401
// - if logged in, allow the request to proceed
// Then a route GET /api/my-orders that only works when logged in.
Your turn
- Distinguish authentication (verifying who you are) from authorization (what you're allowed to do).
- Understand the login flow: verify credentials (against a hash), then establish logged-in state.
- Know how login persists across stateless HTTP: sessions (server + cookie) or tokens (JWT sent each request).
Key points
- Authentication verifies WHO a user is (login); authorization decides what they can DO (next lesson).
- Login: find the user, verify the password against a stored HASH (never plain text), return 401 (generic message) if invalid.
- HTTP is stateless, so login must persist across requests — via sessions (server stores state + browser cookie) or tokens (signed JWT sent each request).
- Auth is security-critical — prefer well-tested libraries/services over rolling your own; always use HTTPS.
Q&A · 0
Enrol to ask questions and join the discussion.
No questions yet — be the first to ask.