0
我使用PassportJS本地策略和護照本地貓鼬。以下是我的登錄腳本:使用護照登錄無法捕獲401條件
// Configure Passport (server.js)
// ---------------------------------------------------------------
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// ---------------------------------------------------------------
。
// POST to /login (authenticate.js)
// ---------------------------------------------------------------
router.post('/login', (req, res) => {
// server-side validation
const errors = {
username: Validator.validateusername(req.body.username),
password: Validator.validatepassword(req.body.password),
};
if (!isEmpty(errors)) return res.send(JSON.stringify({ error: errors }));
passport.authenticate('local')(req, res,() => {
// If logged in, we should have user info to send back
if (req.user) {
const userdata = JSON.stringify(req.user);
const token = jwt.sign({
username: req.user.username,
firstName: req.user.firstName,
lastName: req.user.lastName,
email: req.user.email,
img: req.user.img,
}, process.env.JWT_SECRET);
res.cookie('token', token);
return res.send(userdata);
}
// Otherwise return an error
return res.send(JSON.stringify({ error: 'There was an error logging in' }));
});
});
這工作正常,除非有登錄錯誤。如果因任何原因(401或500)登錄失敗,該腳本是否應該返回There was an error logging in
消息?相反,它只是返回一個401 Unauthorized
?
架構此認證擡頭是:
const { mongoose } = require('../config/dbconfig');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const User = new Schema({
username: {
type: String,
lowercase: true,
required: true,
unique: true,
},
password: {
type: String,
select: false,
required: true,
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
lowercase: true,
required: true,
unique: true,
},
img: {
type: String,
},
}, { timestamps: true });
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User);