简体   繁体   English

如何使用express.js获取remoteUser的请求

[英]How to get the remoteUser for a request with express.js

I'm using a basicAuth middleware in my app, and it works. 我在我的应用程序中使用了basicAuth中间件,并且可以正常工作。

But then, in my routes functions, I would like to get the login that was used by the user to authenticate. 但是,在我的路由功能中,我想获得用户用来验证身份的登录信息。 Assuming req is my request variable, this was supposed to be in req.remoteUser (and later in req.user). 假设req是我的请求变量,则应该在req.remoteUser中(稍后在req.user中)。

But currently both are set to 'true'. 但是目前两者都设置为“ true”。 I check that the middleware is used before calling app.use(app.router), so the req request should be populated ! 我在调用app.use(app.router)之前检查是否使用了中间件,因此应该填充req请求! I also use a bodyParser on the line right after basicAuth, and it populates the request correctly. 我还在basicAuth之后的行上使用bodyParser,它正确填充了请求。

Nothing much on google, only one issue in express github saying that now it works and both req.user and req.remoteUser have the value. 在google上没什么大不了的,在快速github中只有一个问题说现在可以使用了,req.user和req.remoteUser都具有价值。

One needs to provide the username to the callback function (even if the calling code obviously has it in it's context) if we want req.user to be set. 如果我们想要设置req.user,则需要向回调函数提供用户名(即使调用代码显然在其上下文中)。

So intead of doing this (as the great tutorial I followed said) : 因此很有趣(正如我跟随的精彩教程所说):

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass, callback) {
 var result = (user === 'testUser' && pass === 'testPass');
 callback(null /* error */, result);
}));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

One must change the function into : 必须将功能更改为:

app.use(express.basicAuth(function(user, pass, callback) {
  if (user === 'testUser' && pass === 'testPass') {
    callback(null /* error */, user);
  } else {
    callback(null, null);
  }
}));

And for those wondering, yes that means we can't have a user whose name is the empty String (else it will be interpreted as false by express), which seems a shame. 对于那些想知道的人,是的,这意味着我们不能有一个名称为空String(否则它将被express解释为false)的用户,这似乎很可惜。

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

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