如何保护API免受来自第三方站点的恶意代码的攻击

How to safeguard an API against malicious code being sent to it from a 3rd-party site

本文关键字:站点 第三方 恶意 攻击 代码 何保护 保护 API      更新时间:2023-09-26

我有一个内置在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,然后得到保存到我的数据库-但从安全的角度来看,有什么我可以做,以确保这不是恶意代码?

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

在你的express app配置中:

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!' })
}

read express doc 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
      }
   }
});