节点通行证身份验证REST URL

时间:2015-07-06 10:33:39

标签: node.js rest authentication express passport.js

我尝试确保将护照授权给Rest URL。

var isAuthenticated = function (req, res, next) {
  var isAuthenticated = function (req, res, next)
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
};

但是试图得到:

router.get('/edit_grm_user/:user_id',isAuthenticated, function(req, res,next){[...]}

我收到了这个错误:

if (req.isAuthenticated())
        ^   
TypeError: Cannot read property 'isAuthenticated' of null

通过获取没有任何Params的URL,没有错误,即

router.post('/create_grem_user',isAuthenticated, function(req, res, next){[...]}

有人有解决方案吗?

1 个答案:

答案 0 :(得分:1)

想知道为什么要定义两次isAuthenticated

var isAuthenticated = function (req, res, next) {
  var isAuthenticated = function (req, res, next)

无论如何我创建了一个模仿你的上下文的例子:

// Express server
var express = require('express');
var app = express();

// Passport
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

// Middlewares
var flash = require('connect-flash');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var methodOverride = require('method-override');
var session = require('express-session');

var users = [
  {
    id: 1,
    username: 'wilson',
    password: 'secret',
    email: 'wilson.balderrama@gmail.com'
  }
];

function findUserById(id, cb) {
  var idx = id - 1;
  var user = users[idx];

  if (user) {
    cb(null, user);
  } else {
    fn(new Error('User ' + id + ' does not exist.'));
  }
}

function findUserByUsername(username, cb) {
  var userFound = null;

  users.some(function(user) {
    if (user.username === username) {
      userFound = user;
      return true;
    }
  });

  return cb(null, userFound);
}

function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }

  next(new Error('You are not authenticated!.\n'));
}

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  findUserById(id, done);
});

passport.use(new LocalStrategy(function(username, password, done) {
  process.nextTick(function() {
    findUserByUsername(username, function(err, user) {
      if (err) return done(err);
      if (!user) return done(null, false, {message: 'Unknown user ' + username});
      if (user.password !== password) return done(null, false, {message: 'Invalid Password.'});

      return done(null, user);
    });
  });
}));

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
app.use(session({
  secret: 'mysecret',
  resave: false,
  saveUninitialized: true
}));

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

app.post(
  '/auth',
  passport.authenticate('local', {}),
  function(req, res, next) {
    res.send('You just authenticated!\n');
  }
);

app.get('/get-route/:something', isAuthenticated, function(req, res, next) {
  var something = req.params.something;
  res.send('hello from get-route here is your param: '+ something +'\n');
});

app.post('/post-route', isAuthenticated, function(req, res, next) {
  res.send('hello from post-route\n');
});

// handling errors
app.use(function(err, req, res, next) {
  res.status(err.status || 500).send(err.message);
});

app.listen(4040, function() {
  console.log('server up and running');
});

只有经过身份验证的用户才能使用/get-route/:something/post-route

因此,如果您在未经过身份验证的情况下尝试使用/get-route/:something,则会看到一条消息:You are not authenticated!

首先,您需要使用/auth传递用户名和密码,对于此示例,已存储用户:用户名:wilson,密码:secret,因此在您进行身份验证后您可以使用此凭据来使用受保护的路由。

注意:您需要安装以下库:

  "dependencies": {
    "body-parser": "^1.13.2",
    "cookie-parser": "^1.3.5",
    "express": "^4.13.1",
    "connect-flash": "^0.1.1",
    "express-session": "^1.11.3",
    "method-override": "^2.3.3",
    "passport": "^0.2.2",
    "passport-local": "^1.0.0"
  }