LocalStrategy Passport 返回 null
Posted
技术标签:
【中文标题】LocalStrategy Passport 返回 null【英文标题】:LocalStrategy Passport is returning null 【发布时间】:2019-07-31 00:37:09 【问题描述】:我正在尝试使用 Mongoose 和 NodeJS 创建一个护照身份验证应用程序。但是,每当我发送登录请求时,app.js 中的本地策略函数似乎返回 null。代码如下:
// Issue is here:
passport.use(new LocalStrategy((username, password, done) =>
User.findOne(username, password, (err, user) =>
console.log(`\n$username : $password\n`)
console.log(user, err)
return done(null, user); //return done(null, "useraaaa");
);
));
当使用用户名 a 和密码 a 登录时,我的控制台会记录这一点。
输出:
GET /login 304 1503.039 ms - -
GET /stylesheets/style.css 304 2.296 ms - -
a : a
null null
POST /login 302 171.891 ms - 56
GET /login 200 92.865 ms - 501
GET /stylesheets/style.css 304 2.340 ms - -
注意用户的输出是 null,与错误相同。我还在我的 serializeUser
和 deserializeUser
函数中放置了 console.log 语句,但是,代码似乎永远不会到达那里。
如果需要,这里是函数。
passport.serializeUser(function(user, done)
console.log(user);
done(null, user.id);
);
passport.deserializeUser(function(id, done)
User.findById(id).then(user =>
console.log(user);
done(err, user);
);
);
还有:
exports.login = passport.authenticate("local",
successRedirect: "/",
failureRedirect: "/login"
);
我将提供受影响的主要文件。如果需要更多信息,我很乐意提供。
app.js(我使用的是 Express 模板)
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const flash = require("connect-flash");
const expressValidator = require("express-validator");
const indexRouter = require("./routes/index");
const app = express();
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo")(session);
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/User");
mongoose.connect("removed for obvious reasons", useNewUrlParser: true);
const db = mongoose.connection;
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded( extended: false ));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(session(
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
//cookie: secure: true
store: new MongoStore(mongooseConnection: db)
));
app.use(passport.initialize());
app.use(passport.session());
app.use("/", indexRouter);
// Issue is here:
passport.use(new LocalStrategy((username, password, done) =>
User.findOne(username, password, (err, user) =>
console.log(`\n$username : $password\n`)
console.log(user, err)
return done(null, user); //return done(null, "useraaaa");
);
));
// catch 404 and forward to error handler
app.use(function(req, res, next)
next(createError(404));
);
// error handler
app.use(function(err, req, res, next)
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : ;
// render the error page
res.status(err.status || 500);
res.render("./handlers/error");
);
module.exports = app;
user.js(我的路由控制器模块)
const mongoose = require("mongoose");
const expressValidtor = require("express-validator");
const passport = require("passport");
const User = require("../models/User");
const db = mongoose.connection;
const bcrypt = require("bcrypt");
const salt = 10;
mongoose.connect("removed for obvious reasons", useNewUrlParser: true);
db.on("error", console.error.bind(this, "DB Error: "))
db.once("open", () => console.log("Connected to DB"));
// Post Requests
exports.register = (req, res) =>
const username, email, password = req.body;
req.checkBody("username", "Empty username").notEmpty();
req.checkBody("email", "Empty email").notEmpty();
req.checkBody("password", "Empty password").notEmpty();
if (req.validationErrors())
console.log(`Error! $JSON.stringify(req.validationErrors())`);
return req.redirect("/");
;
bcrypt.hash(password, salt, (err, hash) =>
const user = new User();
user.username = username;
user.email = email;
user.password = hash;
user.save((err, response) =>
if (err)
console.error(err);
return res.redirect("/");
;
User.findOne(username, function(err, r)
if (err) throw err;
const id = r._id;
req.login(id, (err) =>
console.log("Success!");
res.redirect("/");
);
);
);
);
;
exports.auth = (req, res, next) =>
return (req.isAuthenticated() ? next() : res.redirect("/login"));
;
passport.serializeUser(function(user, done)
console.log(user);
done(null, user.id);
);
passport.deserializeUser(function(id, done)
User.findById(id).then(user =>
console.log(user);
done(err, user);
);
);
/*
exports.login = async (req, res) =>
res.send(await User.findOne(username: req.body.username, password: req.body.password) || "Not found.");
;
*/
exports.login = passport.authenticate("local",
successRedirect: "/",
failureRedirect: "/login"
);
// Get Requests
exports.home = (req, res) =>
console.log("\n");
console.log(req.user);
console.log(req.isAuthenticated());
console.log("\n");
res.render("home", title: "Auth App");
;
exports.register_gui = (req, res) =>
res.render("register", title: "Register");
;
exports.login_gui = (req, res) =>
res.render("login", title: "Login");
;
exports.profile_gui = (req, res) =>
res.render("profile", title: "Profile")
;
exports.list = async (req, res) =>
res.json(await User.find());
;
User.js(MongoDB 架构)
const mongoose = require("mongoose");
function email_validate(n)
return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w2,3)+$/).test(n);
;
const User = new mongoose.Schema(
username:
type: String,
required: true,
trim: true,
required: "Enter a username."
,
password:
type: String,
required: true,
trim: true,
required: "Enter a password."
,
email:
type: String,
lowercase: true,
trim: true,
unique: true,
required: "Enter a email address",
validate: [email_validate, "Invalid email address."]
);
module.exports = mongoose.model("Users", User);
在进行更改时,我不断收到错误消息,例如 CastError: Cast to ObjectId failed at path "_id" 或 Failed to serialize user into session 或 UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "true" at path "_id" for model "Users" 等等......
【问题讨论】:
【参考方案1】:经过调试,放了无数console.log语句,终于找到了错误。我会将我的解决方案留在这里,以供将来可能的观众使用。
所以在第 69 行,在 user.js 中:
passport.serializeUser(function(user, done)
console.log(user);
done(null, user.id);
);
改为:
passport.serializeUser(function(user, done)
console.log(user);
done(null, user._id); // Underscore before ID.
);
显然,代码试图返回整个文档。这导致缓冲区数据或 null(如果未找到文档)。
解决方案是一个字符。
我现在真的很生气。
【讨论】:
同样的问题。但我的console.log(user);
返回 undefined
以上是关于LocalStrategy Passport 返回 null的主要内容,如果未能解决你的问题,请参考以下文章
Passport.js:LocalStrategy 如何访问用户信息?