I am working on express v4.18.2 I use the jsonwebtoken library, I am trying to perform a login process in one of my middlewares, if successful, perform a redirection and set an "authorization" type header with the bearer token, in the example I use setHeader and req.headers.authorization = token, in the first example it doesn't seem to even set the header, in the second it does while it remains in the middleware, but once the redirect is done the header doesn't seem to persist.
export const validateLoginFromApi = async(req, res, next) => {
const templates = path.join(process.cwd(), "src\\public\\templates")
var credentials = {
username: req.body.username,
password: req.body.password
}
if(credentials.username == secret.username && credentials.password == secret.password){
jwt.sign({credentials}, 'secretkey', (err, token) => {
console.log(req.headers)
res.setHeader("authorization", "bearer "+token).redirect("/NodeBooks/API/books")
});
}else{
res.status(403).sendFile("403.html", {root: templates})
}
}
// route:
.get("/NodeBooks/API/books", verifyWebToken,
getAllbooksFromAPI)
// jsonwebtoken validation
export function verifyWebToken(req, res, next) {
const bearerHeader = req.headers["authorization"];
console.log(req.headers) //<--- header not set
if (typeof bearerHeader === "undefined") {
res.status(403).sendFile('403.html', {root: templates});
}else{
req.token = bearerHeader.split(" ")[1]
jwt.verify(req.token, "secretkey", (err) => {
if (err) {
res.status(403).sendFile('403.html', {root: templates});
}
});
next();
} }