在nodejs

时间:2016-05-05 08:50:56

标签: node.js authentication token

我有一个从mysql数据库中选择用户名的函数,并将结果返回到post请求,如下所示:

function userAuthentication(user){
var deferred = Q.defer();
pool.getConnection(function(err, connection) {
    if (err) {
        var dbError = new Error('No db connection');
        console.log(dbError);
    }
    else {
        var selectUserName = 'SELECT * FROM User WHERE username= '+connection.escape(user)+' ';

        connection.query(selectUserName, function(error, rows){
            if(error){
                console.log(error);
                deferred.reject(error);
            }
            else if(rows.length === 0){
                var countError = new Error('No User Found');
                console.log ("Database.js -> "+ countError);
                deferred.reject(countError);
            }else{
                deferred.resolve(rows);
            }
        });
    }
    connection.release();
});
return deferred.promise;

}

从rout.post请求中调用函数userAuthentication

router.post('/checkAuthentication', function(request, response) {

    database.userAuthentication(request.body.username).then(function(data) {
        if(data[0].RowDataPacket!=0){
            if(bcrypt.compareSync(request.body.password,data[0].password)){
                var token = jwt.sign({
                   username: data[0].username,
                }, superSecret,{
                    expiresInMinutes: 1440
                });

                console.log(token);
                // return the information including token as JSON
                response.json({
                    success: true,
                    message: 'Token Created',
                    token: token
                }); 
            }
            else{
                response.json({ success: false, message: 'Authentication failed. Wrong Password.' });
            }
        }else{
            response.json({ success: false, message: 'Authentication failed. User not found.' });
        }       
    });
});

当我检查输入的用户名和密码是否与mysqlDb中的用户名和密码匹配时,我正在尝试创建令牌,但遗憾的是,未创建令牌;行console.log(token)未将任何结果打印到控制台中。我错过了什么部分???感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您使用的是哪个jwt节点模块?
我认为它不是node-jsonwebtoken,因为它不支持expiresInMinutes,而只支持expiresInMinutes ...

但是,你应该将jwt.sign()调用包含在try / catch块中,以捕获它抛出的任何错误......:

try {
  var token = jwt.sign(
    {
      username: data[0].username,
    },
    superSecret,
    {
      expiresIn: 1440 * 60,
    }
  );
} catch(err) {
  console.error('error signing json web token:', err);
}