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

Using passport session is showing undefined for other api calls. For the callback api it is is showing the value

Below is my code. In authenticationMiddleWare the req.session.passport is undefined. But the value is printing inside the /auth call. So inside the auth call i am setting the session and consoling it in post /api call. But that time the session is not shows user details. I am getting only the below result

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

Below is my code. Please help me to solve the issue

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

An api call from front end

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source