Develop a middleware that retrieves a specific cookie from req.cookies
and validates if it contains a legitimate jwt token. If the token is valid, proceed to call next()
to allow the request routing to move forward. Otherwise, refrain from calling next() and instead use res.redirect("/login")
.
const cookieParser = require('cookie-parser');
app.use(cookieParser(), function(req, res, next) {
let token = req.cookies.myCookieName;
if (token && verify(token)) {
next();
} else {
res.redirect('/login');
}
});
You will need to provide the implementation for the verify()
function which verifies the validity of the token obtained from the cookie. Specify the name of the cookie as demonstrated here with myCookieName
(the name you previously used to store the jwt token).
If the verify()
function requires an asynchronous operation (e.g., querying a database), the code can be adjusted to only trigger the next()
function upon successful completion of the asynchronous callback.