NodeJS & Express authentication middleware not functioning correctly

给你一囗甜甜゛ 提交于 2021-02-08 07:50:11

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/44932028/nodejs-express-authentication-middleware-not-functioning-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!