I was getting Missing CSRF Vulnerability in codeQL to fix that i implemented it , i am using both session base and auth base (Jwt)
STEP 1 - Installed Lusca and Enabled Sessions (CSRF needs them) - npm install express-session
STEP 2 - Use Lusca CSRF Middleware
import session from "express-session";
import lusca from "lusca";
const sessionHandler = session({
store: sessionStore,
secret: secret_env.COOKIE_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
sameSite: "lax",
httpOnly: true,
secure: config_env.NODE_ENV === "production",
maxAge: 1000 * 60 * 60 * 1 // 1 hour
}
});
/ /Enabled CSRF protection AFTER session middleware
const csrfMiddleware = lusca.csrf();
app.use((req, res, next) => {
const isApi = req.path.startsWith("/api") || req.path.startsWith("/cdn") || req.path.startsWith("/v2");
const isFromBrowser = req.headers.accept && req.headers.accept.includes("text/html");
// Skip CSRF for API routes and /login POST if not from browser
const shouldSkipCSRF =
(isApi && !isFromBrowser) ||
(req.path === "/login" && req.method === "POST" && !isFromBrowser);
if (shouldSkipCSRF) {
return next();
}
csrfMiddleware(req, res, (err) => {
if (err) return next(err);
if (typeof req.csrfToken === "function") {
res.locals.csrfToken = req.csrfToken();
}
next();
});
});
STEP 3 - Added CSRF Token to Forms , in ejs files where form + POST METHOD
<input type="hidden" name="_csrf" value="{{ csrfToken }}">
in my routes
app.get('/login', function (req, res) {
res.render('resetPassword', { csrfToken: req.csrfToken() });
});
After implementing CSRF protection using app.use(lusca.csrf()), I started getting 'Missing CSRF token' errors. I was unable to log in to my app, and API calls made through Postman also threw the same error.
Later, I replaced it with a snippet that excludes /api, /v2, /login, and /cdn routes from CSRF protection. Now, I'm facing a CSRF vulnerability again.
Are the steps I followed correct? Please guide me on how to properly solve this issue. Is there a better way to handle CSRF vulnerabilities?"