I read all similar questions in stackoverflow, I checked issues in csurf
github page but I could not figure out the issue. This is the express middlewares file:
const app = express();
const csrfProtection = csrf();
const MongoDBSessionStore = MongoDBStore(session);
const store = new MongoDBSessionStore({
uri: process.env.MONGODB_URI!,
collection: "sessions",
});
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(cors());
app.use(express.json());
app.use(multer({ storage: fileStorage, fileFilter }).single("image")); //arrray for multiple
app.use(express.static(path.join(__dirname, "public")));
app.use("/images", express.static(path.join(__dirname, "images")));
app.use(helmet());
app.use(compression());
app.use(
session({
name: "ts-authentication-app",
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
store: store,
})
);
app.use(csrfProtection);
app.use(flash());
app.use(isAuthroized);
app.use((req, res, next) => {
res.locals.isAuthenticated = req?.session?.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
console.log("token", req.csrfToken());
next();
});
app.use("/admin", adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);
app.get("/500", errorController.get500);
app.use(errorController.get404);
app.use(morgan("combined", { stream: morganLogStream }));
app.use(errorHandler);
I am using ejs template engine. Here is login template.
<form class="login-form" action="/login" method="POST" >
<div class="form-control">
<label for="email">E-Mail</label>
<input
class="<%= validationErrors.find(e => e.param === 'email') ? 'invalid' : '' %>"
type="email"
name="email"
id="email"
value="<%= oldInput.email %>">
</div>
<div class="form-control">
<label for="password">Password</label>
<input
class="<%= validationErrors.find(e => e.param === 'password') ? 'invalid' : '' %>"
type="password"
name="password"
id="password"
value="<%= oldInput.password %>">
</div>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button class="btn" type="submit">Login</button>
</form>
csrfToken
is presented in template. When i change the "hidden" to "text" type, I see the token on the page.I commented out each middleware to see if any of the middlewares is causing the issue but I still get the error.
I logged the req object and
csrfToken: [Function: csrfToken],
is attached to the request object.
I still could not figure out the issue.