Middlewares: Passport library needs more!

We now need to add a few other thing to our application. These are entirely related to how PassportJS library work and have nothing to do with the SAML-based SSO.

Open the terminal and install the following dependencies:

npm install --save express-session body-parser

Add the dependency modules to the top of index.js

const session = require("express-session");
const bodyParser = require("body-parser");
// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
  session({ secret: "use-any-secret", resave: false, saveUninitialized: true })
);
app.use(passport.initialize({}));
app.use(passport.session({}));

I briefly explain the above statements:

Use bodyParser

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));
  • The bodyParser can turn the body of a URL request into a simple object for us to access.
  • The urlencoded() command will handle application/x-www/form-urlencoded values. Passport needs this when handling the IdP response that is directed to our callback POST endpoint.

Use express-session

const session = require("express-session");

app.use(
  session({ secret: "use-any-secret", resave: false, saveUninitialized: true })
);
  • The session store user information on the server side (and session ID on client-side using cookies).
  • The secret value is used to sign a sessionID cookie. The sessionID will reference the server-side session. We can use any value we want for the secret key.
  • The resave value determines whether to save the session value back into the session store after every request, even if it was not changed.
  • The saveUninitailized value is set to true. This means that a session is always saved after it was created even if it did not change.

Setting passport in action

app.use(passport.initialize({}));
app.use(passport.session({}));

The two statements are needed to set passport in action.

Declaring your middleware (all the statements that start with app.use) must be done before declaring the routes (statement that start with app.get or app.post).

Diff
diff --git a/code/index.js b/code/index.js
index 25c43d4..7b66e7c 100644
--- a/code/index.js
+++ b/code/index.js
@@ -1,6 +1,8 @@
 const express = require("express");
 const passport = require("passport");
 const saml = require("passport-saml");
+const session = require("express-session");
+const bodyParser = require("body-parser");
 const fs = require("fs");
 
 const PbK = fs.readFileSync(__dirname + "/certs/cert.pem", "utf8");
@@ -34,6 +36,14 @@ const app = express();
 // Set up port.
 const port = process.env.PORT || 7000;
 
+// Middleware
+app.use(bodyParser.urlencoded({ extended: false }));
+app.use(
+  session({ secret: "use-any-secret", resave: false, saveUninitialized: true })
+);
+app.use(passport.initialize({}));
+app.use(passport.session({}));
+
 // Set up homepage route
 app.get("/", (req, res) => {
   res.send("Test Home Page!");