Подтвердить что ты не робот

Парольная локальная стратегия, сделанная обратным вызовом, не передает сообщение об ошибке json

Я пытаюсь передать сообщение JSON, когда аутентификация завершается с ошибкой, используя выполненный обратный вызов в LocalStrategy, но все, что я получаю, это ответ 401 и "Несанкционированная" строка.

var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var app = express();
app.use(bodyParser.json());
app.use(passport.initialize());

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

var strategy = new LocalStrategy({ usernameField: 'email' },
    function (email, password, done) {
        if (email === '[email protected]' && password === 'pass') {
            return done(null, { email: '[email protected]' });
        } else {
            // never get this json object on the client side when posting invalid credentials
            return done(null, false, { message: 'invalid email or password' });
        }
    }
);

passport.use(strategy);

app.post('/login', passport.authenticate('local'), function(req, res) {
    console.log(req.user);
    res.json(req.user);
});


app.get('/', function(req, res) {
    res.json({ message: 'hello!' });
});

var server = app.listen(3000, function() {
    console.log('api is listening on ', server.address().port);
});

package.json

{
  "name": "passport_example",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.13.3",
    "express": "^4.13.3",
    "passport": "^0.2.2",
    "passport-local": "^1.0.0"
  }
}

Что я делаю неправильно?

4b9b3361

Ответ 1

Значение message, которое вы устанавливаете, сохраняется в сеансе и в режиме вспышки. Я не думаю, что у паспорта есть возможность отправить сообщение об ошибке json. Но вы можете передать обратный вызов в методе authenticate и отправить сообщение оттуда:

app.post('/login', function(req, res, next ){
    passport.authenticate('local', function(err, user, info) {
      if (err) { return next(err) }
      if (!user) { return res.json( { message: info.message }) }
      res.json(user);
    })(req, res, next);   
});