How to authenticate and protect REST API routes using JWT with refersh token rotation

Implement login,register and protect endpoints of your rest api with jwt
1 Overview
After reading this article, you will able to
- Authenticate users with their username/email and password
- Understand the uses of accessToken and refreshToken
- Protect api endpoints from unauthorized clients by validating accessToken
- Allow multi-logins with ability to revoke all session
- Have a template with signup,signin and endpoint protection to kickstart your next rest api
The code is available on github
I suggest to read the full article first and then start coding
The source code structure is as follows
| |
2 Database Schema
- The database is using sqlite so you don’t have to setup any database in your system
- This project uses prisma ORM which will give you typescript support with excellent autocompletion experience
prisma/schema.prisma:
| |
- User and RefreshToken has one to many relationship
- One user can have multiple refreshToken so that logins from multiple devices can be persisted
- Run
npx prisma generateto generate prisma client code. Then runnpx prisma migrate devto create necessary tables according to the schema - Tip : You can use
npx prisma studioto interect with the database in a Web GUI
3 Overview of auth routes
routes/auth.ts:
| |
All routes are prefixed with “/api”
4 Registration
sequenceDiagram
participant c as Client
participant s as Server
participant d as Database
c ->> s: Registration Data
Note over c,s: POST /auth/register
s -) s: validate registration data
alt Invalid Data
s->> c : error message
else Valid Data
s ->> d : Create User
s->>c: success
end
Route : router.post("/auth/register", validateRegistrationData, register)
- The request body should contain username, email and password
- We will create a middleware to validate the registration data
middlewares/validateRegistrationData.ts:
| |
- If an account with the same username or email already exists then return
- Else attach the
userobject toreqand go to the next function
controllers/auth/register.ts:
| |
- Hash the password before storing to the database
| |
5 Log In
Route : router.post("/auth/login", login)
sequenceDiagram
participant c as Client
participant s as Server
participant d as Database
c ->> s: Login Data
Note over c,s: POST /auth/login
s -) d: lookup user
d -) s: Result
alt user doesn't exist
s->> c : User not Found
else user exists
alt credentials mismatch
s ->> c : Wrong password
else credentials match
s -> s : create refreshToken
s -) d : save refreshToken
s ->> c : { accessToken, refreshToken }
end
end
- The request body should contain { username, password }
- Here username field can contain email also, providing the option to log in with both username and email
- Return an error if user doesn’t exist or password is incorrect
- Create accessToken and refreshToken
- Send the refreshToken to be saved as a httpOnly cookie with 30 days validity
- Send the accessToken
controllers/auth/login.ts:
| |
- refreshToken is sensitive data, hence you shouldn’t store it in plain text
- You could either hash it or encrypt it
| |
6 Refresh Access Token
Route : router.get("/auth/refresh", verifyRefreshToken, refreshAccessToken)
sequenceDiagram
participant c as Client
participant s as Server
participant d as Database
c ->> s: refreshToken
Note over c,s: POST /auth/refresh
s -> s : verify refreshToken
alt expired or invalid
s -) c : Unauthorized
else token is valid
s -) d : lookup token
d -) s : result
alt token doesn't exist in db
s-)c : Unathorized
else token exists
s-) d : delete old refrshToken
s-) s : generate new refreshToken
s-) d : save new refreshToken
s-)c : { accessToken, refreshToken }
end
end
- If the token is expired or tampered with then the verification will fail
- If the verification passes but the token doesn’t exist in the db, then you can suspect that someone is trying to use an old token that might be stolen so you return Unauthorized
- Otherwise, delete the refreshToken that was in the cookie of the request, create new token, save it to the database and send set it as a httpOnly cookie, this practice is called refresh token rotation
- Send the accessToken
| |
7 Access protected resource
sequenceDiagram
participant c as Client
participant s as Server
participant d as Database
c ->> s : { accessToken }
Note over c,s : GET /protected
s -> s : verify accessToken
alt invalid token
s-)c : Unauthorized
else valid token
s -) d : query resource
d -) s : result
s -) c : grant access to protected resource
end
As an example, /users can be used as a protected endpoint
Route : router.use("/users", verifyAccessToken, listUsers)
middlewares/verifyAccessToken.ts:
| |
- The client has to send the token in the authorization header following the format
Bearer $token - If the token is not valid, the error will be returned (such as TokenExpiredError or JsonWebTokenError if the token is modified)
- Otherwise the server will query the database and send the list of users to the client
8 Log Out
Route : router.delete("/auth/logout", logout)
8.1 Log out current session
| |
8.2 Log out from All devices
Route : router.delete("/auth/logout", logout_all)
| |
Notice 2 things,
- There’s no check to see if the token exists in db
- Access token verification is skipped
Lets consider a scenario where the client’s cookie is hijacked, so attacker has the refreshToken
- Now he is going to use that refreshToken to get new accessToken
- Which will invalidate the refreshToken of the client from which it was hijacked
- That client may be the legitimate user
- And now that client can’t get any new accessToken
- So if accesToken verification or the check to see if token exists was in db was present then that client wouldn’t be able to logout
9 Testing the api
You can use curl to perform all the requests All the commands listed below is written on tests/api-test-curl.sh
If you use Insomnia, which is an awesome open source api testing tool, you can import all the requests from tests/api-test-insomnia.json
9.1 Register
| |
9.2 Login
| |
Output: {"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNjY2Q2ZjNhLWQxMzItNDQzZi05NWM0LTRmMDJjYmU3ZDRlMSIsInVzZXJuYW1lIjoiZ3I1MjMiLCJlbWFpbCI6ImdyNTIzQGdtYWlsLmNvbSIsImlhdCI6MTY4MTkyOTYyNywiZXhwIjoxNjgxOTI5OTI3fQ.qbfKNvMk2W9JojB7O9CAtshOKoPQ1n2whLWrP4lzEJo"}
- The cookie will be saved in cookie.txt
- Copy the value of accessToken to your clipboard
9.3 Accessing protected endpoint
- Paste the accessToken after Bearer
| |
Output: {"users":[{"id":"3ccd6f3a-d132-443f-95c4-4f02cbe7d4e1","username":"gr523","email":"[email protected]"}]}
- Modify the value of the accessToken
| |
Output {"error":"Invalid Access token","tokenError":"JsonWebTokenError"}
The validity duration of the accessToken is set to 5 minutes, after that you can’t use that token to access protected resources
The response will be {"error":"Invalid Access token","tokenError":"TokenExpiredError"}
You can change the validity duration in utils/genToken.ts
9.4 Refresh Access Token
- Use the value of refreshToken from cookie.txt
| |
Or in linux you can use sed,
| |
Log in again and request refresh, the respone will be {"error":"Invalid Refresh Token","tokenError":"OldToken"}
You have read up to this point, you are ready to take kickstart your next rest-api project. Would appreciate any feedback. Tell me, if you like this style of tutorial or what could be changed to make it better
