【问题标题】:How to safeguard an API against malicious code being sent to it from a 3rd-party site如何保护 API 免受第三方站点向其发送的恶意代码
【发布时间】:2014-03-14 01:10:55
【问题描述】:

我有一个内置于 Wordpress 的表单,它将数据发送到我在 Node 上运行的远程服务器,然后它处理表单并将其发送到 MongoDB

表单的处理类似于:

$('#theForm').submit(function(){
   $.post('http://parthtoserver.com/api/postForm', formdata, function(returnedData){
      if(returnedData === 'Success'){
         // do success stuff here
      }
   });
});

我的 Node API 的代码是:

exports.saveNewUser = function (req, res) {
   console.log("Saving a new user");

   var data = req.body;

   var user = {
       firstName: data.firstName,
       lastName: data.lastName,
       location: data.location,
       email: data.email,
       timezone: data.timezone
   };


   db.users.find({email:user.email}, function(err,record){

    if(err){
        console.log("There was an error finding record " + err);
    }else if (record.length){
        if(record[0].paidStatus === 1){
            console.log("User already exists");
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.send('UserExists'); 
        }
    }else{
        db.users.save(user, function(err, record){
            if(err){
                console.log("There was an error: " + err);
            }else{
                console.log("Updated user");
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "X-Requested-With");
                res.send('Success'); 
            }
        });
    }
   }); 
};

我“假设”另一个站点能够将数据发布到我的 API 并随后保存到我的数据库中并没有什么害处 - 但从安全的角度来看,我能做些什么来确保这不会恶意代码?

【问题讨论】:

  • 简单的解决方案,在您的节点检查标头引荐来源网址。也许也添加一个授权标头。
  • @wayne 很有趣,虽然我不确定如何在 Node.js 中执行此操作。你能写一些代码和解释的答案吗?

标签: javascript node.js api mongodb security


【解决方案1】:

无法判断您是否使用 express,但很可能是。

在您的快速应用配置中:

app.use(express.basicAuth('username', 'password'));

// add your middleware to check referrer
app.use(myCheckReferrer);

function myCheckReferrer(req, res, next) {
  if ( req.get('Referrer') === "somesite.com" )
    next();
  else
    res.json(500, { error: 'Oops, no thank you!' })
}

阅读快递文档here

在客户端需要添加基本的授权头,referrer是自动添加的

$.ajax({
    url: 'http://parthtoserver.com/api/postForm',
    type: 'post',
    data: formdata,
    headers: {
        Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
        // the hash is base64 hash of the string "username:password"
        // without the quote include the colon
    },
    dataType: 'json',
    success: function(returnedData){
      if(returnedData === 'Success'){
         // do success stuff here
      }
   }
});

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    相关资源
    最近更新 更多