我可能漏掉了什么,但根据我找到的所有教程,这是使用express
和passport
+ passport-local
在Node应用程序中进行基本身份验证的方法。我知道这不是最佳实践,我只是想让POC运行起来:
'use strict'
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy
var app = express();
var users = { 'user': 'secretpass'};
passport.use(new LocalStrategy(
function(username, password, done) {
console.log('Username:', username, 'password:', password);
if (!users[username] || users[username] != password) {
console.log('Username:', username, 'password:', password);
return done (null, false);
}
return done(null, {username: username});
}
));
app.use(passport.initialize());
app.get('/', function (req, res) {
res.send ('GET request to root');
});
app.post('/', function (req, res) {
res.send ('POST request to root');
});
app.get('/unauthorized', function (req, res) {
res.status(200).send('GET Forbidden');
});
app.post('/unauthorized', function (req, res) {
res.status(200).send('Post Forbidden');
});
app.post('/webhook',
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/unauthorized'}),
function (req, res) {
res.send ('authenticated!');
}
);
var server = app.listen(8081, function() {
console.log('Server listening at', server.address().address, 'on port', server.address().port);
});
奇怪的是,我在LocalStrategy
构造函数中甚至没有收到那些console.log()语句,所以我猜我真的错过了什么。我尝试使用DHC和Postman发送POST请求,
- 将基本身份验证字段设置为用户名和密码,
- 使用格式为username:password@url的方法,
- 将用户名和密码作为表单数据发送