# How should a Rust server generate and store session IDs?
Source: https://ruststudio.org/community/t/93/how-should-a-rust-server-generate-and-store-session-ids
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, base64 0.22.1, sha2 0.10.9, getrandom 0.2.17, hex 0.4.3, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, sessions, web | Views: 0

## Short answer
Make each session ID 256 random bits from the operating system, send it as an opaque cookie value, and store only its SHA-256 hash on the server beside the session data. A copy of the session table is then useless for impersonating users. The ID carries no meaning and no user data.

## Answer
## Answer
The OWASP Session Management Cheat Sheet asks for session IDs with enough entropy (at least 64 bits of it, and more is better), made by a secure random generator, and meaningless to anyone who sees them. The code below uses 256 bits.

Storing a **hash** of the ID instead of the ID adds protection for the day a backup or a database dump leaks: the hashes cannot be turned back into working cookies. A fast hash is enough here, because the input is already 256 random bits (unlike a password, there is nothing to guess).

```rust title=src/main.rs
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use sha2::{Digest, Sha256};
use std::collections::HashMap;

/// The value that goes in the cookie: 256 random bits.
fn new_session_id() -> String {
    let mut raw = [0u8; 32];
    getrandom::getrandom(&mut raw).unwrap();
    URL_SAFE_NO_PAD.encode(raw)
}

/// The server stores only a hash, so a leaked table cannot be replayed as cookies.
fn lookup_key(id: &str) -> String {
    hex::encode(Sha256::digest(id.as_bytes()))
}

fn main() {
    let mut store: HashMap<String, &str> = HashMap::new();
    let id = new_session_id();
    store.insert(lookup_key(&id), "user 42");

    println!("cookie value is {} characters", id.len());
    println!("stored key is {} characters", lookup_key(&id).len());
    println!("valid id:   {:?}", store.get(&lookup_key(&id)));
    println!("guessed id: {:?}", store.get(&lookup_key("AAAA")));
}
```

```text
cookie value is 43 characters
stored key is 64 characters
valid id:   Some("user 42")
guessed id: None
```

(The HashMap stands in for a database table or a cache. The strings shown are lengths, never values.)

## How to do it
1. Create the ID with `getrandom` and encode it with URL-safe base64.
2. Put the ID in the cookie (see the cookie attributes thread), and the hash in the store with the user ID, creation time and last-seen time.
3. On each request, hash the cookie value and look up the hash.
4. Expire sessions on the server: after an idle period and after an absolute lifetime.
5. Give users a way to sign out everywhere (delete all rows for the user).

## Common mistakes
- Using a counter, a UUID of unknown version, or a hash of the user name as an ID.
- Putting data such as the user's role in the cookie without a signature. If you want data in the cookie, use an authenticated (signed) format.
- Keeping sessions forever.

## Related questions
### Should I use JWTs for sessions?
For a browser application with a single server (or a shared store), a random ID with server-side data is simpler and can be revoked at once. Signed tokens suit cases where other services must verify them without asking you; they then need expiry and a plan for revocation.

### Why a hash and not encryption of the ID?
Encryption needs a key that must be stored and can be lost or stolen together with the table. A one-way hash needs no key, and the server only ever needs to look the value up.

## Sources
- OWASP Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
- `sha2` documentation: https://docs.rs/sha2/0.10.9/sha2/
