2013-12-12 69 views
0

我有一个工作节点应用程序,我需要根据用户通过basicAuth连接到应用程序连接到不同的数据库。NodeJS express basicAuth - 如何将用户名传递给路由功能?

这里有一个例子:

// Authenticating function 
var sgAuth = express.basicAuth(function(user, pass, callback){ 
    if(config.credentials.clients[user] === undefined) { 
    callback(null, false); 
    } else { 
    callback(null, config.credentials.clients[user].password == pass); 
    } 
}); 

// This function needs to know what user has authenticated 
function putEvents(req, res) { 
    //How do I know what user authenticated in this request? 
    var authUser = ???; 
    var table = getUserTable(authUser); 
    ... 
} 
app.post('/put', sgAuth, putEvents); 

在sgAuth存储的用户名来一些变种肯定不会工作,因为可以有来自不同用户的许多传入连接,所以你不能保证其相同的用户, 对?该信息是否可以以某种方式从请求标题中检索?

回答

2

basicAuth() middleware将设置req.userreq.remoteUser一旦授权。

虽然,请注意,回调的第二个参数预计为user,而不仅仅是authorized布尔值。但是,它可以是任何你想要的值,包括user的名称。

callback(null, config.credentials.clients[user].password == pass ? user : null); 

之后,你应该能够与检索:

var authUser = req.user; 
+0

卫生署,我从字面上只是注意到我应该返回用户名! :)'callback(null,config.credentials.clients [user] .password == pass?user:false)' –

+0

请问utils.pause的目的是什么? –

+0

@KatyaS [它似乎是](https://github.com/senchalabs/connect/blob/2.12.0/lib/utils.js#L239-L266)向后兼容['readable.pause()' ](https://github.com/senchalabs/connect/blob/2.12.0/lib/utils.js#L239-L257),这可以防止'req'在等待时传输'data'(任何主体内容) '回调'。 –

0

需要注意的是:BASICAUTH已被弃用

下面的代码:

app.use(express.basicAuth(function(user, pass, callback){ 
    if(config.credentials.clients[user] === undefined) { 
    callback('user not found!!!'); 
    } else { 
    if(config.credentials.clients[user].password === pass) { 
     callback(null, config.credentials.clients[user]); 
    } else { 
     callback('wrong pass!!!'); 
    } 
    } 
}); 

app.post('/put', function putEvents(req, res) { 
    console.log(req.user.name) 
    res.end(); 
}); 
+0

已弃用?嗯,需要调查。谢谢您的回答! –

+0

@KatyaS它已被弃用,但显然不计划被删除。 [来源](https://github.com/senchalabs/connect/blob/2.12.0/lib/middleware/basicAuth.js#L18-L20)。尽管如此,作者仍然建议使用['basic-auth'](https://npmjs.org/package/basic-auth)。 –

相关问题