Nodejs中的Passport身份验证

时间:2017-01-12 22:22:12

标签: javascript node.js html5 express passport.js

以下是我正在处理的代码,但我在执行时遇到错误。 请帮我创建同一页面上的登录和注册表单的路由。 当我使用此代码提交注册表单时,我收到一条错误消息,其中显示错误请求"

var express = require ('express');
var app = express();
var path= require('path');
var bodyParser = require('body-parser');
var mongoose = require("mongoose");
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport();
var smtpTransport = require('nodemailer-smtp-transport');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
var User = require('./models/user');


app.set('port',  process.env.PORT || 3000);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.use(express.static(path.join(__dirname, 'public')));
app.set("view engine", "ejs");
app.use(require('express-session')({
  secret: 'Working on enroll Medicare',
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

mongoose.connect("mongodb://localhost/registration");
app.post('/login-register.html', function(req,res)
{
            var username = req.body.usernameregister;
            var email = req.body.emailregister;
            var password1 = req.body.password1register;
            var password2 = req.body.password2register;
        password1, password2: password2}
        User.register(new User({username: username, email: email}), password1, function(err, user){
          if(err){
            console.log(err);
            return res.render('error');
          }
          passport.authenticate('local')(req, res, function(){
              res.redirect("/secret");
          });
        });
});

登录页面

 app.post("/login-register.html", passport.authenticate('local', {
  succesRedirect: "/secret",
   failureRedirect: "/error"
 }), function(req, res){ });

1 个答案:

答案 0 :(得分:1)

我想你在这里可能有多个问题。以下是一些要检查的事项:

  • 您有passport.use(new LocalStrategy(User.authenticate()));。我不知道User.authenticate()返回什么,但它应该返回一个带有参数function(username, password, done) {...}的函数
  • 看起来您正在使用email作为用户名。您需要将usernameField添加到策略选项中:new LocalStrategy({usernameField: 'email'}, function(email, password, done){...})
  • 我还发现在passport.authenticate函数中使用自定义回调非常有用,可以查看返回的错误是否提供了有关该问题的更多信息:passport.authenticate('local', function(err, user, info) {console.log(err, user, info)})