我正在使用Passport本地策略为Node.js构建身份验证系统。我将所有用户数据保存在SQL Server Express数据库中,而不是在几乎所有Passport实现示例中看到的普通MongoDB中。到目前为止,我已经设法创建了一个有效的用户注册界面,该界面保存了用户名和哈希以及用户的名和姓。我对password.authenticate回调函数的定义有些不满意,只是发现它甚至没有启动(文本“ Passport.authenticate回调已启动。”从未登录到控制台)!我确保安装护照。本地护照,npm快递和快速会议。 我想念什么? (下面的代码) 非常感谢
节点入口点(“ app.js”):
// Import dependencies:
const express = require('express')
const fs = require('fs')
const sql = require('mssql')
const bcrypt = require('bcrypt')
const passport = require('passport')
const session = require('express-session')
const LocalStrategy = require('passport-local').Strategy
// Get port fron environment variables. If not found, default to http standard value:
const port = process.env.PORT || 80
// Create Express app:
const app = new express()
// Express body parser
app.use(express.urlencoded({
extended: true
}))
// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
)
// Passport middleware
app.use(passport.initialize())
app.use(passport.session())
passport.use(
new LocalStrategy({
usernameField: 'userName'
}, (username, password, done) => {
console.log('Passport.authenticate callback was launched.')
var getUserPassword = require('./api/getUserPassword')
getUserPassword({
username: username
}, (queryOutput) => {
if (err) {
console.log(err)
return done(err, false)
}
// Match user
console.log('Query output: ' + queryOutput)
if (!queryOutput[0].Password) {
return done(null, false)
}
// Match password
bcrypt.compare(password, queryOutput[0].Password, (err, isMatch) => {
if (err) throw err
if (isMatch) {
return done(null, {
user: userName,
password: queryOutput[0].Password
})
} else {
return done(null, false)
}
})
})
})
)
passport.serializeUser(function (user, done) {
console.log("User id: " + user.id)
done(null, user.id)
})
passport.deserializeUser(function (id, done) {
done(err, user)
})
// Define static files directory:
app.use('/interfaces', express.static('public'))
app.post('/login', (req, res, next) => {
console.log("req.user = " + req.user)
passport.authenticate('local')(req, res, next)
})
// Check if authenticated:
app.get('*', (req, res, next) => {
if (!req.isAuthenticated()) {
res.redirect('/interfaces/Login/index.html')
}
return next()
}
})
app.post('*', (req, res) => {
console.log("Received post request for path: " + req.path)
console.log("Request body: " + JSON.stringify(req.body))
if (req.path.startsWith("/api")) {
if (!req.isAuthenticated() && req.path != '/login') {
console.log("Attempt to call web service without previous authentication detected.")
res.send('{OUT_Result:"failure"}')
return
}
var apiFunction = require("." + req.path)
apiFunction(req.body, (OUT_Result) => {
console.log("OUT_Result = " + OUT_Result)
res.send(OUT_Result)
})
}
})
// Launch server:
app.listen(port, () => {
console.log('Listening on port ' + port)
})