Does the server remember you, or do you carry a pass?
After you log in, the server must know who you are on every next request. There are two common ways to do this.
HTTP forgets you after every request. It is stateless. So logging in once is not enough: each later request must prove who you are again. Sessions and tokens are two answers to this one problem.
Both methods exist because HTTP has no memory. Which one you pick changes how your system scales and how safe it is.
| Point | Session | Token |
|---|---|---|
| Where is the state? | On the server (store) | In the token, held by the client |
| What does the client hold? | A random session id | A signed token with claims |
| Each request | Look the id up | Verify the signature |
| Scaling servers | Needs a shared store or sticky sessions | Easy, any server can verify |
| Logout / revoke | Instant, delete the record | Hard, wait for expiry or keep a block-list |
| Where it travels | Cookie (sent by the browser) | Authorization header (sent by your code) |
| Size per request | Tiny id | Larger, grows with claims |
| Main attack to watch | CSRF (cookie sent automatically) | XSS stealing the token from storage |
| Term | Meaning in easy words |
|---|---|
| Stateless | The server keeps no memory of earlier requests. HTTP is stateless. |
| Session | A record on the server saying a certain user is logged in. |
| Session id | A random string that points to the session. Kept in a cookie. |
| Cookie | A small piece of data the browser stores and sends back to the same site. |
| Token | A signed piece of data that proves who you are. |
| Bearer token | A token you send in the Authorization header. Whoever βbearsβ it is trusted. |
| Access token | A short-lived token used to call the API. |
| Refresh token | A longer-lived token used only to get a new access token. |
| Sticky session | The load balancer always sends one user to the same server. |
| Revoke | Cancel a login before it would end by itself. |
| CSRF | An attack that tricks your browser into sending its cookie to a site you did not mean to use. |
| XSS | An attack that runs bad script in a page. It can steal tokens kept where scripts can read. |
| Choice | We gain | We lose |
|---|---|---|
| Sessions | Control and instant revoke | A store to run and a lookup each time |
| Tokens | Easy scaling, no lookup | Hard revoke, trust until expiry |
| Short token life | Less damage if stolen | More refreshes |
| Block-list for tokens | Can revoke | You are back to a lookup |