Javascript 验证特定用户的Passport策略
我正在为ReactJS前端构建一个nodeJS后端,我想知道处理特定用户身份验证的最佳方法 到目前为止,我所知道的基本上是,如果一个用户在我的mongoDB集合中,那么身份验证流程将按预期工作 MongoDB模式Javascript 验证特定用户的Passport策略,javascript,node.js,passport.js,Javascript,Node.js,Passport.js,我正在为ReactJS前端构建一个nodeJS后端,我想知道处理特定用户身份验证的最佳方法 到目前为止,我所知道的基本上是,如果一个用户在我的mongoDB集合中,那么身份验证流程将按预期工作 MongoDB模式 OfficeSchema = new Schema({ outlookID: String, displayName: String }); 我正在outlook中使用windows live身份验证。当前的实现如下所示 passport.use( new Outlook
OfficeSchema = new Schema({
outlookID: String,
displayName: String
});
我正在outlook中使用windows live身份验证。当前的实现如下所示
passport.use(
new OutlookStrategy(
{
clientID: keys.OUTLOOK_CLIENT_ID,
clientSecret: keys.OUTLOOK_SECRET,
callbackURL: "/authorize-outlook"
},
async (accessToken, refreshToken, profile, done) => {
const existingUser = await Office.findOne({ outlookID: profile.id });
if (existingUser) {
console.log("existing: ", existingUser);
return done(null, existingUser);
} else {
console.log("no user found!");
return done(null, false);
}
}
)
);
最后,以下是我的路线:
app.get(
"/auth/outlook",
passport.authenticate("windowslive", {
scope: [
"openid",
"profile",
"offline_access",
"https://outlook.office.com/Mail.Read"
]
})
);
app.get(
"/authorize-outlook",
passport.authenticate("windowslive", { failureRedirect: "/login_failure" }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect("/");
}
);
以下是我的问题:
目前我不知道在我的策略中使用done函数的最佳方法,任何提示都会很好。
如何在身份验证流中为未经授权的用户传递错误消息不在db中,静态消息很好您未经授权
在我当前存储用户的outlookID时,将用户添加到此数据库的最佳方法是什么
回答我的任何问题都会大有帮助
谢谢你抽出时间 要保存新用户,只需保存新用户并返回新对象:
Office.findOne({
outlookId: profile.id
}).then(existingUser => {
if (existingUser) {
//hand over the existing object no need to create
done(null, existingUser);
} else {
//assuming that you want to save the new user and grant access
new Office({ outlookId: profile.id }).save().then(newUser => {
//hand over the new user object back to the passport session
//same arguments, new user object
done(null, newUser);
});
}
});
//假设您不想保存用户else{doneerror,null}
关于“完成”对象,可以在策略对象中为此添加错误和信息对象响应
done ("error string","user obj","info string")
但这看起来并不漂亮,因此您可能希望使用官方文件中描述的自定义回调:
然后,您可以让后端将错误对象返回到前端,并进行适当的处理 这应该在评论部分。抱歉,单击了错误的位置。更新了答案-感谢您指出