WeCodeAcademy

Sessions, Tokens and Random Secrets

After you sign in, a site gives your browser a session token, a long random value sent back with every request so the site knows it is you. Anyone who gets the token can act as you, so tokens must be unpredictable and protected.

Use the secrets module, which draws on the operating system's secure randomness. The ordinary random module is predictable and must never be used for tokens, reset links or keys.

Cookies should be marked Secure (only over HTTPS), HttpOnly (hidden from page scripts) and SameSite (limits cross-site sending), and tokens should expire.

Examplepython
Open in editor »
Quick check

Which module should generate session tokens?

Your turn: write the code

Generate a token with secrets.token_hex(16) and print its length in characters.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.