【问题标题】:Authenticating certain users Passport Strategy验证某些用户 Passport 策略
【发布时间】:2019-12-10 02:12:06
【问题描述】:

我正在为 ReactJS 前端构建一个 nodeJS 后端,并且想知道处理身份验证 某些 用户的最佳方式。

到目前为止,我基本上是如果用户在我的 mongoDB 集合中,身份验证流程会按预期工作。

MongoDB 架构

OfficeSchema = new Schema({
  outlookID: String,
  displayName: String
});

我正在使用 windows-live 身份验证(使用 Outlook 进行身份验证)。当前的实现如下所示。

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("/");
    }
  );

这是我的问题:

  1. 目前我不知道在我的策略中使用 done() 函数的最佳方法,任何提示都会很棒。
  2. 如何在我的身份验证流程中为未经授权的用户(不在数据库中)传递错误消息,静态消息很好(“你没有被授权”)
  3. 将用户添加到此数据库的最佳方式是什么(因为我目前为用户存储他们的 OutlookID)

回答我的任何问题都会有很大帮助。

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript node.js passport.js


    【解决方案1】:

    为了保存新用户,您可以简单地保存新用户并返回新对象:

     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 {done(error, null}

    关于完成的对象,可以在你的策略对象中添加错误和信息对象响应。

    done ("error string","user obj","info string")  
    

    这看起来不太漂亮,所以你可能想要使用官方documents 中描述的自定义回调:

    然后您可以让您的后端将错误对象返回到您的前端并适当地处理它。

    【讨论】:

    • 这应该在评论区。
    • 抱歉点击了错误的地方。更新了答案 - 感谢您指出
    猜你喜欢
    • 1970-01-01
    • 2017-05-25
    • 2017-12-28
    • 2014-07-04
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多