11. Auth - Tokens
In this part, you will explore database-stored tokens as another way of implementing authentication in the Snippets API.
This is mainly for conceptual understanding in class and for extension work in the assignment.
We will:
Introduce a
tokenstable.Issue random tokens on login.
Validate tokens on each request.
1. Database: tokens table
Add a tokens table to the Snippets database, for example with columns:
id(primary key)user_id(foreign key tousers.id)role(string)token(string, unique)created_at(timestamp)expires_at(timestamp, optional)
2. Issue a token on login
Extend login (or create a separate /login-token route) so that:
You first verify the username and password using your secure logic.
Generate an encoded token value (using Base64 for the further example).
Insert a new row into the
tokenstable with the user ID and token.Return the token to the client (e.g.
{ "token": "<value>" }).
3. Token auth middleware
Create middleware (e.g. requireTokenAuth) that:
Reads the
Authorizationheader, expecting something likeBearer <token>.Looks up the token in the
tokenstable.(Optionally) checks for expiration.
Attaches the corresponding user to
req.user, or returns401if the token is not valid.
4. Implement role-based routed
Create an /admin rote protected by the role guard, so that:
Only the user with 'admin' role can access the route
Only the authenticated user can access the route
5. Perform the token forgery
In order to demonstrate why simple encoding is not enough for the token - perform the request forgery
Take the token and decode it (examples/token-forgery.js for the full path, CyberChef to go step-by-step)
Change the role in the token from user to admin
Use the newly 'forged' token to enter
/adminroute
6. Suggested exercises
Protect one or more Snippets API endpoints with your token-based middleware.
Implement a
/logout-tokenendpoint that deletes the token from the database.Consider:
How many concurrent tokens you allow per user.
How you might clean up old or expired tokens.
You will build on this concept further in the assignment.
Last updated