护照认证在基本示例中失败 [英] passport authentication failed in basic example

查看:146
本文介绍了护照认证在基本示例中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将这个passport.js示例分解为最基本的元素。我一直收到401(未经授权)的消息,无法弄清楚原因。任何帮助将不胜感激。

I am trying to break down this passport.js example to its most basic elements. I keep getting a 401 (Unauthorized) message and can't figure out why. Any help would be greatly appreciated.

谢谢!

Node.js文件:

Node.js file:

var http = require('http'),
express = require('express'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
flash = require('connect-flash');

var port = process.env.PORT || 8080;

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

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use(new LocalStrategy(
  function(username, password, done) {
   console.log("LocalStrategy working...");
   return done(null, { id: 1, username: 'Joe', password: 'schmo'});
  }
));

var app = express();

app.configure(function(){
  app.use(express.static(__dirname + '/app'));
  app.use(express.cookieParser('big secret'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieSession());
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
});

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

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

app.listen(port);


推荐答案

新express.js的所有用户(4.x与passport.js一起可能会遇到'缺少证书'的麻烦,因为默认情况下不会解析POST数据。要修复它,请安装body-parser npm install body-parser 并在代码中使用:

All users of new express.js (4.x and higher) together with passport.js could experience 'Missing credentials' trouble just because POST data is not parsed by default. To fix it install body-parser npm install body-parser and use in your code:

var bodyParser = require( 'body-parser' );
app.use( bodyParser.urlencoded({ extended: true }) );

来自@ivarni的好点: app.use(bodyParser.urlencoded({ extended:true})); 必须在之前注入任何护照中间件。

Good point from @ivarni: app.use( bodyParser.urlencoded({ extended: true }) ); must be placed before injecting any passport middleware.

这篇关于护照认证在基本示例中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆