【问题标题】:Attach the current user to the request with bearer strategy in passport azure ad在护照天蓝色广告中使用承载策略将当前用户附加到请求
【发布时间】:2020-06-25 03:54:07
【问题描述】:

我有一个使用 express 和 passport 进行身份验证的 NodeJS API 服务器。我正在使用通行证 azure ad bearer 策略与 Microsoft Azure AD 进行身份验证。在文档 (https://github.com/Azure-Samples/active-directory-node-webapi/blob/master/node-server/app.js#L50) 中提供的示例中,所有者 (currentUser) 是全局定义的 javascript 变量。如何将用户附加到请求,以便我可以执行类似的操作

server.post('/user', passport.authenticate('oauth-bearer', {
    session: false
}), function(req, res, next){
    console.log(`I am the current user ${req.user}`);
});

从 OIDC 策略中提到的示例中,我看到了一个 deserializeUserserializeUser 函数,它允许将用户 ID 存储在会话中,但是,在承载策略中,我们没有任何会话维护,因为将对每个传入的请求执行身份验证。

这可能是我理解的差距。我已经浏览了各个库的文档。请帮助我,如果有办法可以做到这一点

【问题讨论】:

    标签: passport.js bearer-token passport-azure-ad


    【解决方案1】:

    以下是示例代码,您可以通过它将 yser 对象嵌入到 request 对象中。因此,当您在 post 回调中执行 ${req.user} 时,您将获得用户对象

    const BearerStrategy = require('passport-azure-ad').BearerStrategy;
    var bearerStrategy = new BearerStrategy(options,
          function(token, done) {
            findById(token.oid, function(err, user) {
              if (err) {
                return done(err);
              }
              if (!user) {
                // "Auto-registration"
                return done(null, token);
              }
              const owner = token.oid;
              return done(null, user, token);
            });
          }
    
    );
    

    【讨论】:

    • 当我尝试这个时,我得到ReferenceError: findById is not defined
    • findById 是应用开发者实现的自定义函数,其中包含可自定义的业务逻辑。
    • 我不清楚,感谢您指出这一点。我仍在学习如何将它们组合在一起。
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2016-08-12
    • 2021-01-17
    相关资源
    最近更新 更多