Skip to content

Replace token logic with jwt

Course: Authentication - chapter 8

Lets change the token logic that we had to use jwts

Add the `jsonwebtoken` library as a dependency - [https://www.npmjs.com/package/jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)
npm install jsonwebtoken
Get rid of our `generateToken` function
function generateToken() {
let options = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let token = "";
for (let i = 0; i < 32; i++) {
// use a simple function here
token += options[Math.floor(Math.random() * options.length)];
}
return token;
}
Create a `JWT_SECRET` variable
const JWT_SECRET = "USER_APP";
Create a jwt for the user instead of generating a token
app.post("/signin", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const user = users.find(user => user.username === username && user.password === password);
if (user) {
const token = jwt.sign({
username: user.username
}, JWT_SECRET);
user.token = token;
res.send({
token
})
console.log(users);
} else {
res.status(403).send({
message: "Invalid username or password"
})
}
});

💡

Notice we put the username inside the token. The jwt holds your state. You no longer need to store the token in the global users variable

In the `/me` endpoint, use `jwt.verify` to verify the token
app.get("/me", (req, res) => {
const token = req.headers.authorization;
const userDetails = jwt.verify(token, JWT_SECRET);
const username = userDetails.username;
const user = users.find(user => user.username === username);
if (user) {
res.send({
username: user.username
})
} else {
res.status(401).send({
message: "Unauthorized"
})
}
})