Passport req.session.passport 总是在其他 api 调用中给出 undefined

Passport req.session.passport always gives undefined on other api calls

其他 api 呼叫使用通行证会话显示未定义。对于回调 api,它显示值

下面是我的代码。在 authenticationMiddleWare 中,req.session.passport 未定义。但是值是在 /auth 调用中打印的。因此,在 auth 调用中,我正在设置会话并在 post /api 调用中对其进行安慰。但是那个时候会话不显示用户详细信息。我只得到以下结果

cookie: {
    path: '/',
    _expires: 2022-05-13T04:53:57.715Z,
    originalMaxAge: 86400000,
    httpOnly: true,
    secure: true,
    ephimeral: true
  }

下面是我的代码。请帮我解决问题

const express = require("express");
const path = require("path");
const app = express();
const bodyParser = require('body-parser');
const loadRouter = require("./routes/index");
app.use(bodyParser.json());
const fs = require("fs");
var session = require("express-session");
 var passport = require("passport");
 var cookieParser = require("cookie-parser");
 var SamlStrategy = require("passport-saml").Strategy;

 app.use(
    session({
      secret: "$$$$",
      saveUninitialized: true,
      resave: true,
      cookie: {
        httpOnly: true,
        secure: true,
        ephimeral: true,
      },
    })
  );
   passport.serializeUser(function (user, done) {
    done(null, user);
  });
  passport.deserializeUser(function (user, done) {
    console.log(user)
    done(null, user);
  });
  app.use(passport.initialize());
  app.use(passport.session());

 app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "callback_url");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type"
  );
  res.setHeader("Access-Control-Allow-Credentials", true);
  res.setHeader("X-Frame-Options", "deny");
  res.setHeader("Cache-Control", "private, no-cache, no-store");
  next();
});

app.use(bodyParser.json({ limit: "200mb" }));
app.use(cookieParser("$$$$"));
app.use(bodyParser.urlencoded({ extended: true }));

passport.use(
   new SamlStrategy(
     {
       callbackUrl:"callbackUrl",
       entryPoint: "entryPoint",
       issuer: 'issuer',
       cert: "cert",
       identifierFormat: 'identifierFormat',
       decryptionPvk: "decryptionPvk",
       protocol: "https://",
       privateCert: "privateCert"
  
     },
     function (profile, done) {
       var user_info = {
         name_id: profile.nameID,
         email: profile.EMAIL,
         manager: profile.Manager,
         employee_type: profile.EmployeeType,
       };
       return done(null, user_info);
     }
   )
 );



app.post(
  "/auth",
  passport.authenticate("saml", {
    failureRedirect: "/login",
    failureFlash: true,
  }),
  function (req, res) {
    req.session.user =req.session.passport.user ;
    res.redirect("/home");
  }
);

 paths_to_be_excluded = [
  "/login",
  "/",
];

var authenticationMiddleWare = function (req, res, next) {
  if (
    paths_to_be_excluded.indexOf(req.path) <= 0 ||
    typeof req.session.passport !== "undefined"
  ) {
       next();
    } else {
      res.redirect("/login");
    }
};

app.get("/login", function (req, res, next) {
    passport.authenticate("saml", {
      failureRedirect: "/",
      failureFlash: true,
    })(req, res, next);
  });
    

app.use(authenticationMiddleWare);


 app.post("/api", function(req,res,next){
  console.log(req.session)
}); 

app.use(function (req, res, next) {
  if (req.session.passport) {
    if (req.session.passport.user.sso_role) {
      res.cookie("user_id", req.session.passport.user.id, {
        maxAge: 90000,
        secure: true,
        httpOnly: true,
      });
    } else {
      res.cookie("user_id", "FORBIDDEN", {
        maxAge: 90000,
        secure: true,
        httpOnly: true,
      });
    }
  } else {
    res.cookie("user_id", "FORBIDDEN", {
      maxAge: 90000,
      secure: true,
      httpOnly: true,
    });
  }
  next();
});

    app.use(express.static(path.join(__dirname, "client/build")));
    app.get("/*", (req, res) => res.sendFile(path.join(__dirname, "/client/build/index.html")));


const PORT =  9001;
app.listen(PORT, () => {
    console.log(`App Running On Port ${PORT}`);
});

来自前端的 api 调用

let url = getURL() + "/api";
            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                credentials: "same-origin",
                body: JSON.stringify({"id": id, "code": code}),
            })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                } 
            })

终于解决了。我们需要使用“cookie-session”而不是“express-session”。所以我只是改变了

var session = require("cookie-session");