Programming Search⌘K

Patterncore

Client session state

Also called Client Session State, cookie session, signed cookie session, cookie store, hidden field state.

Client session state keeps the data of a session on the client, in a cookie, a hidden field or the URL, so the server keeps nothing between requests.

Family
architectural
Intent
Store session state on the client.

Intent

Client session state "Stores session state on the client."1 The server serializes the data of the session, such as the items of a cart or the step of a wizard, and sends it to the client with each response. The client sends it back with the next request. The server keeps nothing between the requests.

Problem

HTTP is stateless. Each request comes alone, but a user works through many requests: a cart grows, a form has many pages, a search has filters. The application must keep this state from one request to the next.

The server can keep the state in its memory or in a database, but then each server must find the state of each session. When many servers share the load, or when a server restarts, this is hard. A server that keeps nothing can serve any request, and a new server can join at once.

Solution

Send the state to the client and let the client hold it. There are three usual places:2

  • The URL. A small state, such as a session ID or a page number, can be a parameter of each link.
  • A hidden field. A form can carry the state in a hidden input field, and the server reads it when the form comes back.
  • A cookie. The browser sends the cookie back with each request to the site, with no work from the page.

The state that comes back is input from the client, so the server must not trust it. The parts of a safe design are:

  • The serialization. The server writes the state as text, such as JSON or a short list of fields, and reads it again on the next request.
  • The signature. The server signs the serialized state with a key that only the server knows, for example with an HMAC. On the next request, it checks the signature and refuses state that the client changed.
  • The encryption, when needed. A signature stops changes, but the client can still read the data. Data that the user must not see must also be encrypted.
  • The size limit. A browser must store only "At least 4096 bytes per cookie",3 so the state must be small.
  request 1   client --------------------------------------> server
              server <- cart "pen:1" + signature ------------  (keeps nothing)
  request 2   client -- cookie "pen:1" + signature --------> server: check, add an item
              server <- cart "pen:1,ink:1" + new signature --

In the following program, the server signs the state and gives all of it to the client. When the client changes the state, the signature does not match, and the server refuses it.

import hashlib
import hmac

SECRET = b"kept on the server"


def to_cookie(state):  # the server signs the state and sends all of it to the client
    return state + "|" + hmac.new(SECRET, state.encode(), hashlib.sha256).hexdigest()


def from_cookie(cookie):  # on the next request, the client sends it back
    state, _, tag = cookie.rpartition("|")
    good = hmac.new(SECRET, state.encode(), hashlib.sha256).hexdigest()
    return state if hmac.compare_digest(tag, good) else None


cookie = to_cookie("step=2;plan=basic")
print("state back:", from_cookie(cookie))
print("changed by the client:", from_cookie(cookie.replace("basic", "gold")))
Output
state back: step=2;plan=basic
changed by the client: None

Example

Each example file is a cart that lives only in a cookie. Each request reads the cookie, checks its HMAC-SHA256 signature, adds one item and sends a new cookie with a new signature. The output shows the data and the first characters of the signature after each of three requests. Then a client changes ink:1 to ink:9 in the cookie, and the server refuses the request because the signature is bad. The server has no table and no map of sessions: the whole cart is in the cookie.

PythonGitHub
import hashlib
import hmac

SECRET = b"server secret, never sent to the client"


def sign(data):
    return hmac.new(SECRET, data.encode(), hashlib.sha256).hexdigest()


def encode(cart):
    """Serializes the session state into the value of a cookie: the data, a bar and the signature."""
    data = ",".join(f"{item}:{qty}" for item, qty in cart.items())
    return data + "|" + sign(data)


def decode(cookie):
    """Checks the signature and gives back the state. A changed cookie gives an error."""
    data, _, tag = cookie.rpartition("|")
    if not hmac.compare_digest(tag, sign(data)):
        raise ValueError("bad signature")
    cart = {}
    for part in filter(None, data.split(",")):
        item, qty = part.split(":")
        cart[item] = int(qty)
    return cart


def handle_add(cookie, item):
    """One request. The server keeps nothing between requests: the state comes in and goes out in the cookie."""
    cart = decode(cookie) if cookie else {}
    cart[item] = cart.get(item, 0) + 1
    return encode(cart)


def show(cookie):
    data, _, tag = cookie.rpartition("|")
    return f"{data}|{tag[:8]}... ({len(cookie)} bytes)"


cookie = None
for item in ["pen", "pen", "ink"]:
    cookie = handle_add(cookie, item)
    print(f"add {item}: cookie {show(cookie)}")

tampered = cookie.replace("ink:1", "ink:9")
try:
    handle_add(tampered, "pen")
except ValueError as e:
    print("a client changes ink:1 to ink:9:", e)

print("cart:", ", ".join(f"{item} {qty}" for item, qty in decode(cookie).items()))
Output
add pen: cookie pen:1|2c06beca... (70 bytes)
add pen: cookie pen:2|bdba40d9... (70 bytes)
add ink: cookie pen:2,ink:1|8bdcc52b... (76 bytes)
a client changes ink:1 to ink:9: bad signature
cart: pen 2, ink 1
  • Verdict: stdlib. hmac.new with hashlib.sha256 signs the serialized cart, and hmac.compare_digest checks the signature in a time that does not depend on where the first difference is.
  • The data part of the cookie is plain text, so the client can read it. A cookie that must be secret needs encryption, not only a signature.
JavaGitHub
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    static final byte[] SECRET = "server secret, never sent to the client".getBytes(StandardCharsets.UTF_8);

    static String sign(String data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET, "HmacSHA256"));
            return HexFormat.of().formatHex(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    // Serializes the session state into the value of a cookie: the data, a bar and the signature.
    static String encode(Map<String, Integer> cart) {
        List<String> parts = new ArrayList<>();
        cart.forEach((item, qty) -> parts.add(item + ":" + qty));
        String data = String.join(",", parts);
        return data + "|" + sign(data);
    }

    // Checks the signature and gives back the state. A changed cookie gives an error.
    static Map<String, Integer> decode(String cookie) {
        int bar = cookie.lastIndexOf('|');
        String data = cookie.substring(0, bar);
        byte[] tag = cookie.substring(bar + 1).getBytes(StandardCharsets.UTF_8);
        if (!MessageDigest.isEqual(tag, sign(data).getBytes(StandardCharsets.UTF_8))) {
            throw new IllegalArgumentException("bad signature");
        }
        Map<String, Integer> cart = new LinkedHashMap<>();
        for (String part : data.split(",")) {
            if (part.isEmpty()) {
                continue;
            }
            String[] kv = part.split(":");
            cart.put(kv[0], Integer.parseInt(kv[1]));
        }
        return cart;
    }

    // One request. The server keeps nothing between requests: the state comes in and goes out in the cookie.
    static String handleAdd(String cookie, String item) {
        Map<String, Integer> cart = cookie == null ? new LinkedHashMap<>() : decode(cookie);
        cart.merge(item, 1, Integer::sum);
        return encode(cart);
    }

    static String show(String cookie) {
        int bar = cookie.lastIndexOf('|');
        return cookie.substring(0, bar) + "|" + cookie.substring(bar + 1, bar + 9) + "... (" + cookie.length() + " bytes)";
    }

    public static void main(String[] args) {
        String cookie = null;
        for (String item : new String[] {"pen", "pen", "ink"}) {
            cookie = handleAdd(cookie, item);
            System.out.println("add " + item + ": cookie " + show(cookie));
        }
        String tampered = cookie.replace("ink:1", "ink:9");
        try {
            handleAdd(tampered, "pen");
        } catch (IllegalArgumentException e) {
            System.out.println("a client changes ink:1 to ink:9: " + e.getMessage());
        }
        List<String> lines = new ArrayList<>();
        decode(cookie).forEach((item, qty) -> lines.add(item + " " + qty));
        System.out.println("cart: " + String.join(", ", lines));
    }
}
Output
add pen: cookie pen:1|2c06beca... (70 bytes)
add pen: cookie pen:2|bdba40d9... (70 bytes)
add ink: cookie pen:2,ink:1|8bdcc52b... (76 bytes)
a client changes ink:1 to ink:9: bad signature
cart: pen 2, ink 1
  • Verdict: stdlib. Mac.getInstance("HmacSHA256") signs the data, HexFormat (Java 17 and later) writes the signature in hex, and MessageDigest.isEqual compares the signatures in constant time.
  • The cart is a LinkedHashMap, and merge adds one to the quantity of an item.
JavaScriptGitHub
const crypto = require("node:crypto");

const SECRET = "server secret, never sent to the client";

function sign(data) {
  return crypto.createHmac("sha256", SECRET).update(data).digest("hex");
}

// Serializes the session state into the value of a cookie: the data, a bar and the signature.
function encode(cart) {
  const data = [...cart].map(([item, qty]) => `${item}:${qty}`).join(",");
  return data + "|" + sign(data);
}

// Checks the signature and gives back the state. A changed cookie gives an error.
function decode(cookie) {
  const bar = cookie.lastIndexOf("|");
  const data = cookie.slice(0, bar);
  const tag = Buffer.from(cookie.slice(bar + 1));
  const expected = Buffer.from(sign(data));
  if (tag.length !== expected.length || !crypto.timingSafeEqual(tag, expected)) {
    throw new Error("bad signature");
  }
  const cart = new Map();
  for (const part of data.split(",").filter(Boolean)) {
    const [item, qty] = part.split(":");
    cart.set(item, Number(qty));
  }
  return cart;
}

// One request. The server keeps nothing between requests: the state comes in and goes out in the cookie.
function handleAdd(cookie, item) {
  const cart = cookie ? decode(cookie) : new Map();
  cart.set(item, (cart.get(item) ?? 0) + 1);
  return encode(cart);
}

function show(cookie) {
  const bar = cookie.lastIndexOf("|");
  return `${cookie.slice(0, bar)}|${cookie.slice(bar + 1, bar + 9)}... (${cookie.length} bytes)`;
}

let cookie = null;
for (const item of ["pen", "pen", "ink"]) {
  cookie = handleAdd(cookie, item);
  console.log(`add ${item}: cookie ${show(cookie)}`);
}

const tampered = cookie.replace("ink:1", "ink:9");
try {
  handleAdd(tampered, "pen");
} catch (e) {
  console.log("a client changes ink:1 to ink:9:", e.message);
}

console.log("cart:", [...decode(cookie)].map(([item, qty]) => `${item} ${qty}`).join(", "));
Output
add pen: cookie pen:1|2c06beca... (70 bytes)
add pen: cookie pen:2|bdba40d9... (70 bytes)
add ink: cookie pen:2,ink:1|8bdcc52b... (76 bytes)
a client changes ink:1 to ink:9: bad signature
cart: pen 2, ink 1
  • Verdict: stdlib. crypto.createHmac("sha256", SECRET) from node:crypto signs the data, and crypto.timingSafeEqual compares the signatures. timingSafeEqual needs two buffers of the same length, so the code checks the lengths first.
  • The cart is a Map, so the items keep the order in which they were added.
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

var secret = []byte("server secret, never sent to the client")

func sign(data string) string {
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(data))
	return hex.EncodeToString(mac.Sum(nil))
}

// line is one item of the cart. A slice keeps the order of the items.
type line struct {
	item string
	qty  int
}

// encode serializes the session state into the value of a cookie: the data, a bar and the signature.
func encode(cart []line) string {
	parts := make([]string, len(cart))
	for i, l := range cart {
		parts[i] = l.item + ":" + strconv.Itoa(l.qty)
	}
	data := strings.Join(parts, ",")
	return data + "|" + sign(data)
}

// decode checks the signature and gives back the state. A changed cookie gives an error.
func decode(cookie string) ([]line, error) {
	bar := strings.LastIndex(cookie, "|")
	data, tag := cookie[:bar], cookie[bar+1:]
	if !hmac.Equal([]byte(tag), []byte(sign(data))) {
		return nil, errors.New("bad signature")
	}
	var cart []line
	for _, part := range strings.Split(data, ",") {
		if part == "" {
			continue
		}
		item, qty, _ := strings.Cut(part, ":")
		n, err := strconv.Atoi(qty)
		if err != nil {
			return nil, err
		}
		cart = append(cart, line{item, n})
	}
	return cart, nil
}

// handleAdd is one request. The server keeps nothing between requests:
// the state comes in and goes out in the cookie.
func handleAdd(cookie, item string) (string, error) {
	var cart []line
	if cookie != "" {
		var err error
		if cart, err = decode(cookie); err != nil {
			return "", err
		}
	}
	for i := range cart {
		if cart[i].item == item {
			cart[i].qty++
			return encode(cart), nil
		}
	}
	return encode(append(cart, line{item, 1})), nil
}

func show(cookie string) string {
	bar := strings.LastIndex(cookie, "|")
	return fmt.Sprintf("%s|%s... (%d bytes)", cookie[:bar], cookie[bar+1:bar+9], len(cookie))
}

func main() {
	cookie := ""
	for _, item := range []string{"pen", "pen", "ink"} {
		var err error
		if cookie, err = handleAdd(cookie, item); err != nil {
			panic(err)
		}
		fmt.Printf("add %s: cookie %s\n", item, show(cookie))
	}
	tampered := strings.Replace(cookie, "ink:1", "ink:9", 1)
	if _, err := handleAdd(tampered, "pen"); err != nil {
		fmt.Println("a client changes ink:1 to ink:9:", err)
	}
	cart, _ := decode(cookie)
	parts := make([]string, len(cart))
	for i, l := range cart {
		parts[i] = fmt.Sprintf("%s %d", l.item, l.qty)
	}
	fmt.Println("cart:", strings.Join(parts, ", "))
}
Output
add pen: cookie pen:1|2c06beca... (70 bytes)
add pen: cookie pen:2|bdba40d9... (70 bytes)
add ink: cookie pen:2,ink:1|8bdcc52b... (76 bytes)
a client changes ink:1 to ink:9: bad signature
cart: pen 2, ink 1
  • Verdict: stdlib. hmac.New(sha256.New, secret) signs the data, and hmac.Equal compares the signatures in constant time.
  • The cart is a slice of line values, not a map, because the order of a range over a map is not defined.
RustGitHub
// The Rust standard library has no SHA-256 or HMAC, so this file has small versions of both.
// A real program would use a tested crate, such as hmac and sha2.

const K: [u32; 64] = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

fn sha256(input: &[u8]) -> [u8; 32] {
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ];
    let mut msg = input.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&((input.len() as u64) * 8).to_be_bytes());
    for block in msg.chunks(64) {
        let mut w = [0u32; 64];
        for i in 0..16 {
            w[i] = u32::from_be_bytes([block[4 * i], block[4 * i + 1], block[4 * i + 2], block[4 * i + 3]]);
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }
        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
        for i in 0..64 {
            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
            let ch = (e & f) ^ (!e & g);
            let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]);
            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
            let maj = (a & b) ^ (a & c) ^ (b & c);
            let t2 = s0.wrapping_add(maj);
            hh = g;
            g = f;
            f = e;
            e = d.wrapping_add(t1);
            d = c;
            c = b;
            b = a;
            a = t1.wrapping_add(t2);
        }
        for (x, y) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
            *x = x.wrapping_add(y);
        }
    }
    let mut out = [0u8; 32];
    for (i, x) in h.iter().enumerate() {
        out[4 * i..4 * i + 4].copy_from_slice(&x.to_be_bytes());
    }
    out
}

fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut k = [0u8; 64];
    if key.len() > 64 {
        k[..32].copy_from_slice(&sha256(key));
    } else {
        k[..key.len()].copy_from_slice(key);
    }
    let mut inner: Vec<u8> = k.iter().map(|b| b ^ 0x36).collect();
    inner.extend_from_slice(data);
    let mut outer: Vec<u8> = k.iter().map(|b| b ^ 0x5c).collect();
    outer.extend_from_slice(&sha256(&inner));
    sha256(&outer)
}

const SECRET: &[u8] = b"server secret, never sent to the client";

fn sign(data: &str) -> String {
    hmac_sha256(SECRET, data.as_bytes()).iter().map(|b| format!("{:02x}", b)).collect()
}

// Compares in a time that does not depend on where the first difference is.
fn same(a: &str, b: &str) -> bool {
    a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0, |acc, (x, y)| acc | (x ^ y)) == 0
}

// Serializes the session state into the value of a cookie: the data, a bar and the signature.
fn encode(cart: &[(String, u32)]) -> String {
    let data: Vec<String> = cart.iter().map(|(item, qty)| format!("{}:{}", item, qty)).collect();
    let data = data.join(",");
    let tag = sign(&data);
    format!("{}|{}", data, tag)
}

// Checks the signature and gives back the state. A changed cookie gives an error.
fn decode(cookie: &str) -> Result<Vec<(String, u32)>, String> {
    let (data, tag) = cookie.rsplit_once('|').ok_or("no signature")?;
    if !same(tag, &sign(data)) {
        return Err("bad signature".to_string());
    }
    let mut cart = Vec::new();
    for part in data.split(',').filter(|p| !p.is_empty()) {
        let (item, qty) = part.split_once(':').ok_or("bad item")?;
        cart.push((item.to_string(), qty.parse::<u32>().map_err(|e| e.to_string())?));
    }
    Ok(cart)
}

// One request. The server keeps nothing between requests: the state comes in and goes out in the cookie.
fn handle_add(cookie: Option<&str>, item: &str) -> Result<String, String> {
    let mut cart = match cookie {
        Some(c) => decode(c)?,
        None => Vec::new(),
    };
    match cart.iter_mut().find(|(i, _)| i == item) {
        Some(line) => line.1 += 1,
        None => cart.push((item.to_string(), 1)),
    }
    Ok(encode(&cart))
}

fn show(cookie: &str) -> String {
    let (data, tag) = cookie.rsplit_once('|').unwrap();
    format!("{}|{}... ({} bytes)", data, &tag[..8], cookie.len())
}

fn main() {
    let mut cookie: Option<String> = None;
    for item in ["pen", "pen", "ink"] {
        let next = handle_add(cookie.as_deref(), item).unwrap();
        println!("add {}: cookie {}", item, show(&next));
        cookie = Some(next);
    }
    let cookie = cookie.unwrap();
    let tampered = cookie.replace("ink:1", "ink:9");
    if let Err(e) = handle_add(Some(&tampered), "pen") {
        println!("a client changes ink:1 to ink:9: {}", e);
    }
    let cart: Vec<String> = decode(&cookie).unwrap().iter().map(|(i, q)| format!("{} {}", i, q)).collect();
    println!("cart: {}", cart.join(", "));
}
Output
add pen: cookie pen:1|2c06beca... (70 bytes)
add pen: cookie pen:2|bdba40d9... (70 bytes)
add ink: cookie pen:2,ink:1|8bdcc52b... (76 bytes)
a client changes ink:1 to ink:9: bad signature
cart: pen 2, ink 1
  • Verdict: library. The Rust standard library has no SHA-256 and no HMAC, so the file has short versions of both, and same compares the signatures in constant time. A real program would use tested crates, such as hmac and sha2.
  • decode returns a Result, and the ? operator passes a bad signature back to the caller.

Consequences

Benefits.

  • A stateless server. Any server can handle any request, so load balancing, fail-over and restarts are simple.
  • No storage on the server. There is no session table to grow and nothing to clean up. The Django documentation notes that the cookie backend does not have this problem, "because the session data is stored by the users’ browsers."4
  • Fast. The Rails documentation says that its cookie-based store "is dramatically faster than the alternatives."5
  • The state survives a restart of the server.

Liabilities.

State with no signature can be changed by the client. In the following program, the cookie holds the role of the user as plain text. The user edits the cookie, and the server believes the new role.

This code runs but gives a wrong answer on purpose.

cookie = "user=ann;role=customer"  # Wrong: the state goes to the client with no signature


def role(cookie):
    return dict(part.split("=") for part in cookie.split(";"))["role"]


print("role before:", role(cookie))
cookie = cookie.replace("customer", "admin")  # the client can edit its own cookie
print("role after the client edits the cookie:", role(cookie))
Output
role before: customer
role after the client edits the cookie: admin

Sign the state with a key that only the server knows, and check the signature on each request. Better still, keep data such as a role on the server, and send only a signed ID.

The client can read the state. In Django, "The session data is signed but not encrypted"4 and "When using the cookies backend the session data can be read by the client."4 Flask says the same of its sessions: "the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing."6

Size. Each request carries the whole state. RFC 6265 asks that "Servers SHOULD use as few and as small cookies as possible to avoid reaching these implementation limits and to minimize network bandwidth due to the Cookie header being included in every request."3

No freshness and no logout. The server cannot tell that a cookie is old, so a client can send back an older state. Django warns that the MAC "cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client."4 Because the server keeps no record, "cookie-based sessions are not invalidated when a user logs out."4

Deserialization of untrusted data. Never read the state with a deserializer that can make arbitrary objects, such as pickle. A signature helps only while the key stays secret. See Deserialization of untrusted data.

When not to use it

When the state is large. A cart with hundreds of lines, or a document that the user edits, does not fit in a cookie. Use Server session state or Database session state.

When the state is secret or sensitive. Data that the user must not see or keep needs encryption, and data that must be removed at logout needs a record on the server.

When the server must be able to end a session. To log a user out at once, or to block a stolen session, the server must keep a record of the session.

Signed cookies. The state is readable, but a signature stops changes. This is the cookie backend of Django and the session of Flask.46

Encrypted cookies. The state is encrypted and signed. In Rails, "encrypted cookies cannot be altered or read by users."5

Only a session ID on the client. The client holds only a random ID, and the state is on the server. This is the usual mix: client session state for the ID, and Server session state or Database session state for the data.

Related patterns. The serialized state is a kind of Data transfer object for the session. The serialization itself is Serialization.

Known uses

  • Ruby on Rails. "This cookie-based session store is the Rails default."5 A CookieOverflow exception is raised when the session is larger than 4096 bytes.5
  • Django, with the signed_cookies session engine.4
  • Flask, whose session object "is implemented on top of cookies for you and signs the cookies cryptographically."6

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Client Session State, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 6, Session State; Chapter 17, Session State Patterns, Client Session State
  3. RFC 6265, HTTP State Management Mechanism, April 2011, section 6.1 Limits
  4. Django 5.2 documentation, How to use sessions, Using cookie-based sessions
  5. Ruby on Rails API, ActionDispatch::Session::CookieStore, description
  6. Flask documentation, Quickstart, Sessions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/67ATSC/text.yaml