I’m trying to protect a page for authenticated users, but I came across an error where my back-end does not receive the cookies and authorization headers.
In searching for the error I found a method to solve it, using:
headers: {
Authorization: `Bearer ${TOKEN}`
}
But when I set the cookie in the back-end I use "httpOnly: true"
for better security, so I can’t access the token from the client side (front-end). That’s why I configure “credentials: true” in both cors and axios so that in every request they automatically send the token
Cors Config (back-end):
const corsConfig = {
origin: [process.env.BASE_URL],
credentials: true,
allowedHeaders: ["Content-Type"],
}
Axios Config (front-end):
const api = axios.create({
withCredentials: true,
baseURL: BASE_URL
})
Cookie JWT Auth middleware:
const cookieJwtAuth = async (req, res, next) => {
try {
console.log(req.headers);
const [, token] = req.headers.authorization.split(" ");
if (!token) {
return res.status(401).json({
statusCode: 401,
message: "Token not found",
});
}
const decodedToken = await jwt.verify(token, process.env.SECRET);
if (!decodedToken.username) {
return res.status(401).json({
statusCode: 401,
message: "Username not found in token",
});
}
req.user = decodedToken;
next();
} catch (err) {
res.clearCookie("auth");
return res.status(400).json({
statusCode: 400,
message: "Not authorized",
})
}
}
I noticed the error in the console.log line when the request through the front-end is different from the request through Insomnia
Note: When testing the route on Insomnia it works propretly
console.log(req.headers) – front-end:
{
host: 'localhost:666',
connection: 'keep-alive',
'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
accept: 'application/json, text/plain, */*',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
'sec-ch-ua-platform': '"Windows"',
origin: 'http://127.0.0.1:5500',
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://127.0.0.1:5500/',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6'
}
console.log(req.headers) – Insomnia:
{
host: 'localhost:666',
cookie: 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkVSSUNaQVJETyIsImlkIjoiMyIsImlhdCI6MTcxNDcwMDUzNiwiZXhwIjoxNzE0NzAwNTk2fQ.yo_H_yvxIQC1cwphXoXiVnOKWPNTL74dDS26gLgA9oc; auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkVSSUNaQVJETyIsImlkIjoiMyIsImlhdCI6MTcxNDc4MDQ1MiwiZXhwIjoxNzE0ODY2ODUyfQ.mTRXYF6O7fJEGvw8NqebbMy0q1SwUYRtKe0AIhVpyeQ',
'user-agent': 'insomnia/9.1.0',
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkVSSUNaQVJETyIsImlkIjoiMyIsImlhdCI6MTcxNDc4MDQ1MiwiZXhwIjoxNzE0ODY2ODUyfQ.mTRXYF6O7fJEGvw8NqebbMy0q1SwUYRtKe0AIhVpyeQ',
accept: '*/*'
}
I made several changes to the cors and axios settings thinking that this was the error. I Also tried adding to AllowedHeaders “Authentication” in Cors configuration
But I realized that the error was only in the front-end as it is not possible to use the split method if the value is undefined as in this case.
I still think it’s just a small modification, but I still need a little help.
If you need more details about the problem or any part of the code, let me know in the comments
Eric Zardo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.