如何修复阻止注册用户登录的护照本地身份验证错误

Posted

技术标签:

【中文标题】如何修复阻止注册用户登录的护照本地身份验证错误【英文标题】:How to fix passport local authentication error that prevents registered users from logging in 【发布时间】:2021-01-15 16:04:23 【问题描述】:

我花了一些时间来弄清楚为什么我的护照本地身份验证的代码不能正常工作,但我没有 可以。该程序具有用户名字段和密码字段。因此人们可以使用他们的用户名和密码进行注册。代码中的问题在于 在登录部分。如果我使用任何注册的用户名和密码登录,浏览器会显示 Data not found 而不是显示 重定向页面的内容。请问,这个错误可能是什么原因造成的。该程序的代码如下所示。

验证架构文件:


const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
    
const userSchema = mongoose.Schema(
    username: 
    type: String,
    required: true
    ,
    password: String,
);

userSchema.plugin(passportLocalMongoose);
    
const User = mongoose.model("User", userSchema);
module.exports = User;

设置

const express = require("express");
const Post = require("./../models/post");
const User = require("./../models/user")

//Connecting mongoose with mongodb

const  mongoDB = "mongodb://localhost/blog";
mongoose.connect("mongodb://localhost/blog", 
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
);
const db = mongoose.connection;

//Adding success or error message to node console
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function()
    console.log("Connection successful");
);

const router = express.Router();
const bodyParser = require("body-parser");
router.use(bodyParser.json());

//const User = require("../models/user");
var passport = require("passport");
var localStrategy = require("passport-local").Strategy;

//Passport configuration
router.use(require("express-session")(
   secret: "A programmer",
   resave: false,
   saveUninitialized: false
));

router.use(passport.initialize());
router.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

验证路由:

router.get("/new", isLoggedIn, (req, res) => 
   console.log(req.params)
   res.render("new", post: new Post());
)

router.get("/register", async(req, res)=>
   res.render("register");
)

router.post("/register", function(req, res)
   req.body.username
   req.body.password
   var newUser = new User (username: req.body.username)
   User.register(newUser, req.body.password, function (err, user)
      if(err)
         console.log(err)
         return res.render("register")
      
      passport.authenticate("local")(req, res, function()
         res.redirect("login");
      )
   )
)

router.get("/login", function(req, res)
   res.render("login");
);

router.post("/login", passport.authenticate("local", 
   successRedirect: "new",
   failureRedirect: "login",
), (req, res, next)=>

)
router.get("/logout", (req, res)=>
   req.logout();
   res.redirect("login")
)
function isLoggedIn(req, res, next)
   if(req.isAuthenticated())
      return next
   
   res.redirect("login")

登录模板文件(login.ejs)

<%- include ('partials/header') %>
    <div class="container mb-4 mt-4">
        <div>
        <span class="loginIcon float-right"><img src="/public/images/e73b6446-110b-413d-9c0a-1d05fa9acc6e.jfif" ></span>
        <h2 class="text-center">Login</h2>
        </div>
    <form action="posts/login" method="POST">
    <div class="form-group">
        <label for="author">Username</label>
        <input required type="text" name="username"  class="form-control" id="username" placeholder="Please enter your Username">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input required type="password" name="password" class="form-control" id="title" placeholder="Please enter your password">
    </div>
    <div class="text-center">
    <button type="submit" class="btn btn-outline-primary btn-lg btn-block mb-2">Submit</button>
    <a href="/" class="btn btn-outline-secondary btn-lg btn-block">Cancel</a>
    </div>
</form>
    <div class="text-center"><a href="/posts/register">Sign up if you don't have an account</a></div>
    
</div>
    <%- include ('partials/footer') %>

【问题讨论】:

【参考方案1】:

一段时间后,我能够找出为什么当注册用户尝试登录时浏览器显示未找到的数据。问题来自中间人。由于 failureRedirect 工作正常,问题来自中间人的下一个方法。应该是:

function isLoggedIn(req, res, next)
   if(req.isAuthenticated())
      return next()
   
   res.redirect("login")

当返回的 next 函数末尾的括号被省略时,会出现此问题。因此,它应该是 return next() 而不是return next

【讨论】:

以上是关于如何修复阻止注册用户登录的护照本地身份验证错误的主要内容,如果未能解决你的问题,请参考以下文章

节点护照错误:未知身份验证策略“本地登录”

在服务器端护照js本地用户身份验证后,如何在客户端使用cookie显示用户信息?

本地护照和本地护照猫鼬的身份验证错误

mongoose 中本地护照的身份验证错误

如何使用身份验证管理器修复“错误凭据”错误?

无法运行护照登录策略。身份验证错误~ TypeError: Cannot read property 'authenticate' of undefined