Session-based Authentication — Auth

Session-based auth: the server keeps the session data in a store (memory, file, database, Redis), and the browser only holds a random session ID in an…

Siti types her password once. After that she can open her report card, move between pages, reload, and nobody asks for the password again. Yet HTTP remembers nothing from one request to the next. So who remembers?

In session-based authentication, the server does. It remembers who is logged in in its own notebook, called the session store, and only gives the browser a random number, called the session ID, inside a cookie. It's like the bag check at a supermarket: your bag stays behind the counter, and you hold a numbered card. The card says nothing about you. When you leave, the clerk takes the card back and empties the shelf.

The flow, request by request

Log in, open the report, log out. This is the HTTP conversation in School Portal, exactly what the Lab shows (your session ID in the Lab is random, so it differs):

POST /login HTTP/1.1
Host: portal.school.test
Content-Type: application/json

{"email": "[email protected]", "password": "secret123"}

HTTP/1.1 200 OK
Set-Cookie: sid=3f9c2a7e51d04b8c9e16a2f07d3b5c41; Path=/; Max-Age=7200; HttpOnly; Secure; SameSite=Lax

GET /students/1/grades HTTP/1.1
Host: portal.school.test
Cookie: sid=3f9c2a7e51d04b8c9e16a2f07d3b5c41

HTTP/1.1 200 OK

POST /logout HTTP/1.1
Cookie: sid=3f9c2a7e51d04b8c9e16a2f07d3b5c41

HTTP/1.1 204 No Content
Set-Cookie: sid=; Path=/; Max-Age=0
  1. The password matches, so the server writes a new entry in the session store: 3f9c2a... -> { userId: 1, role: "student" }.
  2. The server sends Set-Cookie, and the browser keeps it. From now on the browser attaches Cookie: sid=... to every request to portal.school.test, automatically, with no JavaScript.
  3. On each request, the server looks the ID up in the store. Found means Siti. Not found or expired means 401.
  4. Logging out deletes the entry in the store. Max-Age=0 tells the browser to drop its cookie too.

The session data lives on the server. The browser only holds its ID.

The flags on the cookie

Why each flag matters, and what happens without it, is covered in the Cookie Security lesson of the Security track.

The server code

const sessions = new Map(); // session store: id -> session data

function newSessionId() {
  const bytes = crypto.getRandomValues(new Uint8Array(16)); // 128 random bits
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}

function login(user, oldId) {
  if (oldId) sessions.delete(oldId); // regenerate: the pre-login ID is thrown away
  const id = newSessionId();
  sessions.set(id, { userId: user.id, role: user.role, expiresAt: Date.now() + 7200 * 1000 });
  return `sid=${id}; Path=/; Max-Age=7200; HttpOnly; Secure; SameSite=Lax`;
}

function currentUser(id) {
  const session = sessions.get(id);
  if (!session || session.expiresAt < Date.now()) return null; // becomes a 401
  return session;
}

function logout(id) {
  sessions.delete(id); // the server forgets, so the old cookie is useless
  return "sid=; Path=/; Max-Age=0";
}

One server, two servers

Now School Portal runs on two servers, and each server keeps sessions in its own memory. A memory store is known only to the server that holds it. Siti logs in on server A, so her entry sits in A's memory. Her next request lands on server B, B looks for the ID, doesn't find it, and answers 401. On server B, Siti counts as not logged in.

There are two ways out:

Way How it works Note
Shared store Every server reads the same store: Redis or a database The usual choice
Sticky sessions The load balancer always sends one browser to the same server If that server restarts, all its sessions are gone

The store options: memory (fast, but lost on restart and not shared), file (simple, one server), database (lasting, shared, a little slower), Redis (fast and shared, needs a Redis server).

In Laravel

Laravel already provides all of it. A correct login and logout:

public function login(Request $request)
{
    $credentials = $request->validate(['email' => 'required|email', 'password' => 'required']);

    if (! Auth::attempt($credentials)) {
        return back()->withErrors(['email' => 'Email or password is wrong']);
    }

    $request->session()->regenerate(); // a new ID after login
    return redirect()->intended('/report');
}

public function logout(Request $request)
{
    Auth::logout();
    $request->session()->invalidate();      // delete the session in the store
    $request->session()->regenerateToken(); // a new CSRF token
    return redirect('/');
}

Storing and reading your own session data:

session()->put('class', '11 Science 2');  // or session()->put(['class' => '11 Science 2'])
session()->get('class');                  // '11 Science 2'
session()->forget('class');
session()->flash('status', 'Grade saved'); // only for the next request

The settings live in config/session.php: driver (default database, or redis or file), lifetime 120 minutes, http_only true, same_site lax, and secure from SESSION_SECURE_COOKIE. The cookie is named laravel_session, and Laravel encrypts its value before sending it.

⚠️ Sessions that won't die, or die on their own

TL;DR: Session-based auth: the server keeps the session data in a store (memory, file, database, Redis), and the browser only holds a random session ID in an HttpOnly; Secure; SameSite=Lax cookie. On each request the server looks the ID up: found means logged in, not found means 401. Regenerate the ID at login, delete the entry on the server at logout. More than one server needs a shared store such as Redis, or sticky sessions. In Laravel: Auth::attempt, session()->regenerate(), session()->invalidate(), and session()->put() to store data.

⚡ The data is on the server, the browser holds a number

Meaning: The server records who is logged in in its own session store (memory, file, database or Redis). The browser only gets a random number in a cookie, called the session ID. Like the bag check at a supermarket: your bag stays behind the counter, and you hold a numbered card.

⚡ Log in: a new ID, then Set-Cookie

Write:

function login(user, oldId) {
  if (oldId) sessions.delete(oldId); // regenerate: the pre-login ID is thrown away
  const id = newSessionId();
  sessions.set(id, { userId: user.id, role: user.role, expiresAt: Date.now() + 7200 * 1000 });
  return `sid=${id}; Path=/; Max-Age=7200; HttpOnly; Secure; SameSite=Lax`;
}

Meaning: On every later request the browser attaches Cookie: sid=... by itself, with no JavaScript. The server looks the ID up in the store: found means Siti, not found or expired means 401. HttpOnly keeps scripts on the page from reading the cookie.

⚡ Logging out must delete on the server

Guess first: logout only sends Max-Age=0 so the browser drops its cookie. Is someone who copied the old cookie still logged in?

Yes. The entry in the store is still alive, so the old ID is still recognised. Logout must delete the entry on the server too: sessions.delete(id).

Meaning: Delete the entry in the store, then tell the browser to drop its cookie.

⚡ Two servers need one store

Meaning: A memory store is known only to the server that holds it. Siti logs in on server A, her next request lands on B, and B answers 401. The way out: every server reads the same store, such as Redis.

What you will learn