【问题标题】:req.isAuthenticated() is returning true even after wrong password is entered即使输入了错误的密码,req.isAuthenticated() 也会返回 true
【发布时间】:2020-04-02 03:50:29
【问题描述】:

我正在使用护照本地策略对用户进行身份验证,这是我的登录代码:

app.post("/login",function(req,res){
  const user = new model({
    username:req.body.username,

    password:req.body.password,
  });


        req.login(user, function(err) {
          if (err) {
            res.render("login",{error: err});
            } else {
              passport.authenticate("local")(req, res, function() {

                res.redirect("/dashboard");
              });
              }
      });

}); 

现在,如果我输入了错误的密码,则会出现未经授权的消息,然后如果我转到仪表板路由,则 req.isAuthenticated() 为真,

这是我的仪表板代码:

app.get("/dashboard",function(req,res){
  if(req.isAuthenticated()){
//mywork
}

如何解决这个问题以及如何/在哪里处理未经授权的消息?

passport.use(model.createStrategy());
passport.serializeUser(model.serializeUser());
passport.deserializeUser(model.deserializeUser());

app.use(session({

secret: "secret",
resave: false,
   saveUninitialized: false,

}));

【问题讨论】:

    标签: node.js express session passport.js passport-local


    【解决方案1】:

    您正在使用req.login。你知道它是做什么的吗?以下是您处理问题的方式,首先您要创建一个策略(显然您有一个用户模型)。

    const User = require('../models/User');
    
    passport.serializeUser((user, done) => {
      done(null, user.id);
    });
    
    passport.deserializeUser((id, done) => {
      User.findById(id, (err, user) => {
        done(err, user);
      });
    });
    
    /**
     * Sign in using Email and Password.
     */
    passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
      User.findOne({ email: email.toLowerCase() }, (err, user) => {
        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { msg: `Email ${email} not found.` });
        }
        if (!user.password) {
          return done(null, false, { msg: 'Your account was registered using a sign-in provider. To enable password login, sign in using a provider, and then set a password under your user profile.' });
        }
        user.comparePassword(password, (err, isMatch) => {
          if (err) { return done(err); }
          if (isMatch) {
            return done(null, user);
          }
          return done(null, false, { msg: 'Invalid email or password.' });
        });
      });
    }));
    

    然后在你的控制器中你可以创建一个登录方法:

    /**
     * POST /login
     * Sign in using email and password.
     */
    exports.postLogin = (req, res, next) => {
      const validationErrors = [];
      if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' });
      if (validator.isEmpty(req.body.password)) validationErrors.push({ msg: 'Password cannot be blank.' });
    
      if (validationErrors.length) {
        req.flash('errors', validationErrors);
        return res.redirect('/login');
      }
      req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false });
    
      passport.authenticate('local', (err, user, info) => {
        if (err) { return next(err); }
        if (!user) {
          req.flash('errors', info);
          return res.redirect('/login');
        }
        req.logIn(user, (err) => {
          if (err) { return next(err); }
          req.flash('success', { msg: 'Success! You are logged in.' });
          res.redirect(req.session.returnTo || '/');
        });
      })(req, res, next);
    };
    

    为了确保您的路线经过身份验证:

    app.get('/', homeController.index);
    app.get('/login', userController.getLogin);
    app.post('/login', userController.postLogin);
    app.get('/logout', userController.logout);
    app.get('/forgot', userController.getForgot);
    app.post('/forgot', userController.postForgot);
    app.get('/reset/:token', userController.getReset);
    app.post('/reset/:token', userController.postReset);
    app.get('/signup', userController.getSignup);
    app.post('/signup', userController.postSignup);
    app.get('/account/verify', passportConfig.isAuthenticated, userController.getVerifyEmail);
    app.get('/account/verify/:token', passportConfig.isAuthenticated, userController.getVerifyEmailToken);
    app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
    

    还有护照策略会话的应用设置:

    app.use(session({
      resave: true,
      saveUninitialized: true,
      secret: process.env.SESSION_SECRET,
      cookie: { maxAge: 1209600000 }, // two weeks in milliseconds
      store: new MongoStore({
        url: process.env.MONGODB_URI,
        autoReconnect: true,
      })
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());
    app.use((req, res, next) => {
      if (req.path === '/api/upload') {
        // Multer multipart/form-data handling needs to occur before the Lusca CSRF check.
        next();
      } else {
        lusca.csrf()(req, res, next);
      }
    });
    app.use(lusca.xframe('SAMEORIGIN'));
    app.use(lusca.xssProtection(true));
    app.disable('x-powered-by');
    app.use((req, res, next) => {
      res.locals.user = req.user;
      next();
    });
    app.use((req, res, next) => {
      // After successful login, redirect back to the intended page
      if (!req.user
        && req.path !== '/login'
        && req.path !== '/signup'
        && !req.path.match(/^\/auth/)
        && !req.path.match(/\./)) {
        req.session.returnTo = req.originalUrl;
      } else if (req.user
        && (req.path === '/account' || req.path.match(/^\/api/))) {
        req.session.returnTo = req.originalUrl;
      }
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2020-07-21
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多