"message":"invalid csrf token","code":"EBADCSRFTOKEN"

"message":"invalid csrf token","code":"EBADCSRFTOKEN"

我在 Whosebug 中阅读了所有类似的问题,我在 csurf github 页面中检查了问题,但我无法找出问题所在。这是快速中间件文件:

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);

我正在使用 ejs 模板引擎。这是登录模板。

<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>

我还是没弄清楚问题。

您似乎没有为表单使用的编码类型设置适当的正文解析器 - 即默认 x-www-form-urlencoded.

Express 提供了这样一个主体解析器,只需像这样将它添加到您的中间件堆栈中即可:

app.use(express.urlencoded({ extended: false }))