我有一个页面,只有授权用户才能访问,但是我代码中的身份验证检查始终返回false(重定向到登录页面的/ clipboard)
我尝试实现各种模块,例如session
模块,并正确设置了express和password.js的顺序,我觉得它应该可以工作,但是由于某种原因,我无法获得身份验证以返回true
const router = express.Router();
router.get("/", (_: express.Request, res: express.Response) => {
res.render("index", {
title: "Daniell | Home"
});
});
router.get("/clipboard", (req: express.Request, res: express.Response) => {
res.render("clipboard/index", {
title: "Login"
});
});
router.get("/clipboard/:username", (req: express.Request, res: express.Response) => {
if (req.isAuthenticated()) {
return res.send(`Welcome ${req.query.username}`);
}
res.redirect("/clipboard");
});
// views setup
this.express.set("view engine", "ejs");
this.express.set("views", path.join(__dirname, "../views"));
// static files
this.express.use(express.static(path.join(__dirname, "./public")));
this.express.use(express.static(path.join(__dirname, "../node_modules/bootstrap/dist")));
this.express.use("/", router);
this.express.use(bodyParser.urlencoded({ extended: true }));
this.express.use(cookieParser());
// passport
const MongoStore = connectMongo(session);
this.express.use(session({
secret: "panda warrior",
resave: true,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
this.express.use(passport.initialize());
this.express.use(passport.session());
passport.serializeUser((user: { id: string }, done) => {
done(undefined, user.id);
});
passport.deserializeUser((id: string, done) => {
User.findById(id, (error: Error, user: string) => {
done(error, user);
});
});
// mongoose
mongoose.connect(process.env.MONGO_PATH, { useNewUrlParser: true });
interface IUser extends mongoose.Document {
username: string;
password: string;
}
const UserSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true }
});
const User = mongoose.model<IUser>("User", UserSchema);
// authentication
passport.use(new Strategy(
(username: string, password: string, done) => {
User.findOne({ username: username }, (error, user) => {
if (error) {
return done(error);
}
if (!user) {
return done(undefined, false);
}
if (user.password != password) {
return done(undefined, false);
}
return done(undefined, user);
});
})
);
this.express.post("/clipboard",
passport.authenticate("local", { failureRedirect: "/clipboard" }),
(req: express.Request, res: express.Response) => {
res.redirect(`/clipboard/user?username=${req.user.username}`);
});
使用上面的代码,我转到localhost:3000/clipboard
,并输入了有效的凭据,但是我被重定向到同一页面,而不是包含成功消息的页面