Lukon
Lukon

Reputation: 265

NodeJS & Express authentication middleware not functioning correctly

I am attempting to run the function isUserAuthenticated on every request to the server by requiring it in app.js and 'using' it as so: app.use(authenticate.isUserAuthenticated).

I have an /authenticate callback route that is being POSTED to by our SAML Identity Provider which contains the information required to validate the user and the session. This is what is inside my authenticate.js file:

module.exports = router;
module.exports.isUserAuthenticated = function(req, res, next) {
    console.log(req.cookies.subject);
  if (req.cookies.subject) {
      console.log(req.cookies.subject)
    return next();
    } res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
}

As referenced, this authentication function is being required and used in app.js: authenticate = require('./routes/authenticate'), and app.use(authenticate.isUserAuthenticated).

The problem: No matter what variation of the if statement to verify if the subject cookie is present in the request, the authentication check is not being fired and the redirect to the IDP authentication route is not being redirected too. The console.log checks in the code above are returning:

undefined, and {}.

Authentication was working on a single route when I was using the isUserAuthenticated function manually like this: router.use('/', isUserAuthenticated, function(req, res, next) {..., but I am trying to use this function globally so I don't have to manually incorporate this middleware on each route.

Any advice/suggestions would be greatly appreciated. Thank you.

Upvotes: 1

Views: 1849

Answers (2)

sbharti
sbharti

Reputation: 979

as suggested in comment,

you can move the isUserAuthenticated function to app.js. It'd look something like this

app.use(function(req, res, next) {
  if (req.cookies.subject) {
    next();
    } 
else 
    res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");

})

This will process all the requests before they are forwarded to the routes later.

Upvotes: 1

Arpit Solanki
Arpit Solanki

Reputation: 9931

A middleware needs to be set on router object if you are using express js

router.use(isUserAuthenticated)

Don't forget to put this on the top of your routes file.

See the difference between app level and router level middleware here

Upvotes: 1

Related Questions