简体   繁体   English

如何与护照一起使用快速基本身份验证

[英]How to use express basic auth alongside passport

I'm using Passport with a NodeJS/Express app for user authentication, and it's working great. 我将Passport与NodeJS / Express应用程序结合使用以进行用户身份验证,并且效果很好。 However, I want to lock down certain deployments with basic authentication (similar to .htaccess basic HTTP auth on Apache), such as a staging server. 但是,我想使用基本身份验证(类似于登台服务器)来锁定某些部署(类似于Apache上的.htaccess基本HTTP身份验证)。

To be more clear, I have a dev environment which runs everything locally. 更清楚地说,我有一个开发环境,可以在本地运行所有内容。 I have a test environment which kicks-off with every build. 我有一个测试环境,每个构建版本都会启动。 I have a staging environment to use with black box testing, and finally a production environment. 我有一个用于黑匣子测试的过渡环境,最后是一个生产环境。 I would like to apply the basic auth to the staging environment so that a user/pass combo is required to even reach it. 我想将基本身份验证应用于登台环境,以便甚至需要一个用户/密码组合。 All other functionality should be available once the basic auth is passed. 通过基本身份验证后,所有其他功能都应该可用。

I've tried Express' built-in basicAuth, which works well, except that it populates req.user, which is what Passport uses. 我尝试了Express内置的basicAuth,它很好用,只是它填充了Passport使用的req.user。 Thus, my sessions get polluted so that logging in and out with Passport no longer works correctly since it thinks a user has already logged in. 因此,我的会话受到污染,因此使用Passport登录和注销不再正常,因为它认为用户已经登录。

Here's a snippet of where I'm using basicAuth: 这是我使用basicAuth的代码段:

// Basic auth (for staging env)
// Note: I'm checking for my dev env just to test this
if (process.env.NODE_ENV == 'development') {
    app.use(express.basicAuth('dev', 'abc123'));
}

Is there another method I can use in lieu of basicAuth, or another way I can use basicAuth to make this happen? 是否可以使用另一种方法代替basicAuth或使用basicAuth做到这一点?

Perhaps you can do this: 也许您可以这样做:

if (process.env.NODE_ENV == 'development') {
  app.use(express.basicAuth('dev', 'abc123'));
  app.use(function(req, res, next) {
    req.basicAuthUser = req.user;
    req.user = null;
    next();
  });
}

So when a user got authenticated with basic authentication, req.user is stored somewhere (if you need it) and subsequently reset to null as to not confuse Passport. 因此,当用户通过基本身份验证进行身份验证时, req.user会存储在某个位置(如果需要),然后将其重置为null以免混淆Passport。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM