NodeJS Passport Autehntication错误请求

时间:2015-11-20 00:49:33

标签: node.js passport.js

我正在尝试关注如何使用护照与节点的教程视频但由于某种原因我一直收到错误的请求错误,我尝试了护照网站上的一些示例,包括自定义回调以及一些建议来自论坛,但没有运气。似乎该程序甚至没有调用passport.use(我试过放一个控制台消息,但它根本没有出现)。

护照配置:

module.exports = function(){
    var passport = require('passport');
    var passportLocal = require('passport-local');
    var userService = require('../services/user-service');

    passport.use(new passportLocal.Strategy({usernameField: 'email'}, function(email, password, next){

        console.log('========TEST=======');

        userService.findUser(email, function(err, user){

            if(user){
                console.log(user.email + ' found!');
            }

            if(err){
                return next(err);
            }
            if(!user || user.password != password){
                return next(null,false);
            }
            next(null, user);
        });
    }));

    passport.serializeUser(function(user, next){
        next(null, user.email);
    });

    passport.deserializeUser(function(email, next){
        userService.findUser(email, function(err, user){
            next(err, user);
        });
    });
};

用户路线:

var express = require('express');
var router = express.Router();
var userService = require('../services/user-service');
var passport = require('passport');

/* GET users listing. */
router.get('/', function(req, res, next) {

  res.render('users', {
    title: 'Users',
    description: 'This is the users page'
  });
});

router.get('/login', function(req, res, next) {
  res.render('users/login', {
    title: 'Login',
    description: 'Please login'
  });
});

router.post('/login', passport.authenticate('local'), function(req, res, next){
  res.redirect('/items');
});

module.exports = router;

用户服务:

var User = require('../models/user').User;

exports.addUser = function(user, next){
    var newUser = new User({
        firstName: user.firstName,
        lastName: user.lastName,
        email: user.email.toLowerCase(),
        password: user.password
    });

    newUser.save(function(err){
        if(err){
            return next(err);
        }
        next(null);
    });
};

exports.findUser = function(email, next){
    User.findOne({email: email.toLowerCase()}, function(err, user){
      next(err, user);
    });
};

WWW

    #!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('main');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

app.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var expressSession = require('express-session');

var config = require('./config.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var items = require('./routes/items');

var passportConfig = require('./auth/passport-config');
passportConfig();


mongoose.connect(config.mongoUri);

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(expressSession(
  {
    secret: 'I will achieve my GOALS!',
    saveUninitialized: false,
    resave: false
  }
));

app.use(passport.initialize());
app.use(passport.session());


app.use('/', routes);
app.use('/users', users);
app.use('/items/', items);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

1 个答案:

答案 0 :(得分:0)

尝试更改app.js文件中的护照变量,以使用您的配置而不是护照模块。

public String toString() {
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 1; i <= word.length(); i++) {
        stringBuffer.append(word).append("\n");
    }
    return stringBuffer.toString();
}

从app.js

中删除以下内容
var passport = require('./auth/passport-config');