So I’ve been trying to implement JWT authorization for my project, and there’s this specific step that I’ve been stuck for hours… So I have a middleware setup to try and verify the access token which is given when the user successfully logs in, and when I grab the token from the authorization header using this line: const authHeader = req.headers.authorization
it’s always undefined. I tried watching more videos and they literally do the same but it always works fine on their part, they are able to grab the token and the further verify it, but here I am just following every step they do but its “UNDEFINED” 🙁
This is the code that verifies the credentials of the user and once its successful, it generates a refresh token that will be stored on the user’s cookies, and an access toke which will be sent as a json object.
the jwt object in my code is from jsonwebtoken library.
export async function verifyLogin(req, res) {
const { username, password } = req.body;
const foundUser = await findUsername(username);
if (!foundUser) {
return res.status(401).json({ invalidUsername: "Username not found" });
}
const passwordMatch = await bcrypt.compare(password, foundUser.password);
if (!passwordMatch) {
return res.status(401).json({ invalidPassword: "Invalid Password" });
}
const accessToken = jwt.sign(
{ id: foundUser.librarian_id },
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: "100s" }
);
const refreshToken = jwt.sign(
{ id: foundUser.librarian_id },
process.env.REFRESH_TOKEN_SECRET,
{ expiresIn: "1d" }
);
await insertRefreshToken(foundUser.librarian_id, refreshToken);
res.cookie("jwt", refreshToken, {
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000,
});
This is the middleware to verify the token
export function verifyToken(req, res, next) {
const authHeader = req.headers.authorization; //THIS LINE IS THE PROBLEM
//const authHeader = req.headers['authorization']
//some tutorials do this instead, and it still doesn't work in my code
//next-step (check the token, if it exists split it...)
//this part is not yet implemented
try {
const decoded = jwt.verify(token, process.env.ACESS_TOKEN_SECRET);
req.id = decoded.id;
next();
} catch (error) {
res.clearCookie("jwt");
res.redirect("/login");
}
}
And this is one of the routes that uses uses that middleware
app.get("/information", verifyToken, (req, res) => {
res.render("info.ejs");
});
I tried getting the token this way
const token = req.cookies.jwt;
I mean it works but it gets the refresh token anyway since that was the token that was stored on the browser, but what I’m trying to get was the accessToken sent as json object.