HACKORY
Language · English
← All chapters
HACKORY / Open library

Session, cookies and tokens

When you sign in, the site gives you something like a concert wristband: a value you show with every request so you do not type your password again. That value can be a cookie or a token, and the time during which the site recognizes you is called a session.

New here? Try the first lesson without an account

How it works

A cookie is a small value the server asks the browser to store; the browser sends it automatically with every request to that site. A token is a similar value the app adds on its own, usually in a header. Being hard to guess or forge is not enough: the server must still check that it is still valid and what it allows.

Expected behavior

The session cookie says which account is making the request; with that, the server checks whether that account may see the invoice it asked for.

What can go wrong

The cookie still works after you tap “Sign out,” or the server accepts it for an action that account should not be able to perform.

What to observe

With a test account, request one of your own resources before and after signing out, and compare both responses.

Common false positive

A signed cookie, with a seal that reveals any change, can be authentic and still be expired or grant too many permissions.

Why it matters

Whoever gets someone else’s cookie or token can act as that person while it remains valid, just like someone getting in with another person’s wristband.

How to fix it

Send these values only over encrypted connections (https), make them expire, replace them at sign-in, and check on the server the permission for each action.

Understand it step by step

Why sessions exist

HTTP remembers nothing between one request and the next: each message arrives on its own. So it does not ask for your password at every click, the server gives you a value after you sign in and recognizes it in the following requests. The cookie travels automatically with each request to its site; the app adds the token, usually in a header. Both are credentials, that is, proofs of identity: whoever holds them can act as your account.

Valid is not the same as allowed

A cookie or token can be authentic and unaltered and still not work for everything. The server must check that it has not expired and that the account has permission for what it asks. A valid session for Ana proves she is Ana, but it does not authorize her to see Bruno’s invoice.

Signing out and changing the key

Tapping “Sign out” should invalidate the cookie on the server, not just delete it from your browser. At sign-in, or when moving to an account with more permissions, the site should issue a new cookie and discard the old one. Check it with your test account: seeing that the “Sign out” button worked on the screen is not enough.

Recommend this chapter to a friend