Passport authentication not working in sails.js application

℡╲_俬逩灬. 提交于 2019-12-18 21:26:33

问题


I have a Sails JS application. I am trying to setup authentication using Passport.js authentication layer sails-generate-auth. I have configured my app by following the steps given in their documentation.

But when I lift my sails app, authentication is not working. I am able to access the controllers, even when I am not logged in (It's not redirecting to my login page).

I added a console.log statement in api/policies/passport.js as follows:

module.exports = function (req, res, next) {
  passport.initialize()(req, res, function () {
    passport.session()(req, res, function () {
      res.locals.user = req.user;
      console.log(req.user); // added by me
      next(); 
    });
  });
};

Now, when I access controllers before login or after logout, its printing undefined. But when I am logged in, its printing my user data. Any idea why it is not checking for authentication?

I am using local authentication strategy and I have commented out all others (twitter, facebook...)


回答1:


Passport doesn't have a policy to deny access to a controller. For this, you have to create another policy.

See this link for more details.




回答2:


The above answer provides useful information. I want to elaborare on that.

sails-generate-auth, by default doesn't deny access to controllers if the user is not logged in. For that, you can create another policy in api/policies/. For example: create sessionAuth policy as follows:

module.exports = function(req, res, next) {
  if (req.user) {
    return next();
  }

  return res.forbidden('You are not permitted to perform this action.');
};

Instead of showing forbidden page, you can also render login page. For that you need access to AuthController.login. So, add the policies in config/policies as follows:

'*': ['passport', 'sessionAuth'],

'auth': {
  '*': ['passport']
}

This helps to restrict access all the controllers except auth controllers such as login, logout and register, if the user is not logged in.



来源:https://stackoverflow.com/questions/27168229/passport-authentication-not-working-in-sails-js-application

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