The Essentials on JWTs, Access & Refresh Tokens
Once a user's password has been securely stored during signup, the next crucial step is ensuring only authenticated users can access their specific resources. Modern backend architecture manages this access by issuing a token or cookie upon successful login.
Login & Token Issuance
After signup, the user must re-verify their credentials (a process called Login). Login first authenticates the user against their stored credential, and upon successful verification authorizes them (give access) to their data and features.
Login retrieves a user password, and check the hashed value against the one stored in the database. A token will be issued if a match is found. This token - a secure, temporary and unique string of data - is issued by a server to a client after every successfuly login. The token is then sent with subsequent requests to gated resources, eliminating the need to repeatedly send the username and password. The token acts as a proof of the client's indentity and their current authorization.
Tokens are communicated in two primary ways: as Cookies reserved on the server or as Bearer tokens to be managed by the client.
For traditional web app, using a Cookie is fine. However, for non-browser clients like a mobile app or native desktop applications, Bearer tokens are a better alternative.
Authentication with Cookies
One of the ways to communicate tokens with clients is with Cookies. Let's look at a step by step implementation.
Focus on the app.post() method. We'll be using abstract Node/Express code to demonstrate these concepts
jsimport crpto from "crypto;";
// ...application setup...
app.post("/login", (req, res) => {
// 1. Get user credentials from the Request Body
const credential = req.body;
// 2. Find if the user exists in the database using their username
const user = DATABASE.find((c) => c.username === credential.username);
if (!user) return res.status(400).json({ error: "User don't exist" });
// ...The password verification logic will go here...
res.status(200).json({ message: "User found" });
});
// ...rest of application code...
To appreciate our progress, let's add some protected routes to the mix.
js// ...some exiting lines of code...
app.get("/protected", authenticatedToken, (req, res) => {
res.status(200).json({ message: "welcome to your protected route" });
});
app.get("/non-protected", (req, res) => {
res.status(200).json({ message: "welcome to an unprotected route" });
});
Let's add some extra logic to app.post()
jsapp.post('/login', (req, res)=> {
const credential = req.body;
const user = DATABASE.find(c => c.username === credential.username);
if(!user) return res.status(400).json({error: 'User don\'t exist'})
let hasMatch = false;
const hashed = await hashFn(credential.password, user.salt)
hasMatch = hashed === user.password;
if(!hasMatch) return res.status(400).json({error: 'Username and password incorrect'})
// Token generation and cookie setting will go here
res.status(200).json({message: 'User found'});
})
After comfirming the username and password matches, we must now attach a token to tell the client a match exist by sending a cookie.
jsapp.post('/login', (req, res)=> {
const credential = req.body;
const user = DATABASE.find(c => c.username === credential.username);
if(!user) return res.status(400).json({error: 'User don\'t exist'})
let hasMatch = false;
const hashed = await hashFn(credential.password, user.salt)
hasMatch = hashed === user.password;
if(!hasMatch) return res.status(400).json({error: 'Username and password incorrect'})
// NOTE: 'token' is currently a non-unique placeholder string!
res.cookie('cookie-name', 'token', {
httpOnly: true, // Prevents client-side JS access, mitigating XSS
secure: true, // Ensures cookie is only sent over HTTPS
sameSite: true, // Protects against Cross-Site Request Forgery (CSRF)
maxAge: 1000 * 60 * 60 // 1 hour expiration (in milliseconds)
})
res.status(200).json({message: 'User found'});
})
With this implementation, the server will auto attach this cookie on subsequent visit to the server.
Run in curl
- Run the server,
- signup with
curl -X POST localhost:3003/signup -H "Content-Type: application/json" -d '{"username": "janedoe", "password": "janedoesess"}' - login with
curl -v -X POST localhost:3003/login -H "Content-Type: application/json" -d '{"username": "janedoe", "password": "janedoesess"}'
In the header output, you should see the Set-Cookie property with our cookie.
After one hour, the browser will automatically delete the cookie forcing the user to login again.
If you have been following, you must have noticed a serious security flaw: Our token is hard-coded and not unique. Attackers could easily forge the "token" string and have access to user's resources. To make our token unique, we would employ the JSON Web Token (JWTs) package. A JWT is a compact, URL-safe means of representing claims to be transferred between two parties.
We replace the placeholder string with a signed JWT.
js// ... application code ...
app.post("/login", async (req, res) => {
const credential = req.body;
// ... user and password verification logic ...
if (!hasMatch)
return res.status(400).json({ error: "Username and password incorrect" });
// SECURITY: Never include the password in the JWT payload
delete credential.password;
const token = jwt.sign(credential, `${process.env.MY_SECRET}`, {
expiresIn: "1hr",
});
res.cookie("cookie-name", token, {
httpOnly: true,
secure: true,
sameSite: true,
maxAge: 1000 * 60 * 60,
});
return res.status(200).json({ message: "User found" });
});
Authentication with Bearer Tokens
We have covered cookie-based delivery; now we will examine the Bearer Token method.
A Bearer Token is simply an Access Token prefixed with the word "Bearer" and included in the Authorization HTTP header. The prefix signals that the token holder ("the bearer") is authorized to access the resource.
When using Bearer Tokens, the token is returned to the client in the response body instead of being sent separately as a cookie in previous examples:
js// ... application code ...
app.post("/login", async (req, res) => {
// ... verification logic ...
const token = jwt.sign(credential, `${process.env.MY_SECRET}`, {
expiresIn: "1hr",
});
return res.status(200).json({
message: "User found",
data: token,
});
});
The client application receives the token and must store it (e.g., in localStorage). For every protected API call, the client explicitly sets the Authorization header with the Bearer Token.
Run example in curl
- sign up
- log in (you'll receive the token in the response body)
- try access a protected route with:
curl -v -X GET localhost:3003/protected -H "Authorization: Bearer JWT-TOKEN"
You should be able to see the protected response.
Now that we implemented log in, did you notice The JWT (expiresIn) and Cookie (maxAge) both define an expiration property. Access Token expiry is typically kept short (e.g., 15-30 minutes). This minimizes the time an attacker has if the token is compromised.
When an Access Token expires, the traditional method forces the user to log in again. This is a poor user experience. Next, let's talk Refresh Access Tokens.
What happens when Access token expires
To mitigate the user experience of having to log in again after an access token experience, Refresh Tokens are used to obtain a new Access Token without requiring the user to re-enter their credentials. Unlike short-lived Access Tokens, Refresh Tokens are long-lived (e.g., days or weeks) and are securely stored (often in an HttpOnly cookie or database). When the Access Token expires, the client sends the valid Refresh Token to a dedicated refresh endpoint to be exchanged for a new Access Token.
jsfunction AuthenticateMiddleware(req, res, next) {
let token = "";
// 1. Check for cookie (server-managed)
// this else..if is used when a cookie or jwt is used
// normally you would stick with one
if (req.cookies["cookie-name"]) {
token = req.cookies["cookie-name"];
// 2. Check for Authorization header
} else if (req.headers.authorization) {
token = req.headers.authorization.split(" ")[1];
//3. Gets the token after 'Bearer'.
}
if (token) {
//4. The jwt.verify() function checks the signature and the expiration date
const user = jwt.verify(token, `${process.env.MY_SECRET}`, (err, user) => {
if (err) {
// Token is invalid (tampered with) or expired
res.clearCookie("cookie-name");
return res.status(403).json({ error: "token is invalid or expired" });
}
});
req.user = user;
next();
} else {
return res.status(401).json({ error: "no authorization found" });
}
}
With the use of refresh token, comes another challenge. Because Refresh Tokens are long-lived, their compromise presents a significant security risk. An attacker with a compromised Refresh Token could perpetually generate new Access Tokens. To challenge, Refresh Token Rotation is used in defence. When the client requests a new Access Token, the server must invalidate the old Refresh Token while simultaneously issuing both a new Access Token and a new Refresh Token. This ensures that if the Refresh Token is ever compromised, it can only be used once before being invalidated.