首页 > 解决方案 > NODE.JS - 检查对象中是否有意外字段

问题描述

我正在将带有用户信息的对象从客户端发送到我的服务器:

const newUserData = {
    name, 
    username,
    gender,
    avatar,
} 

我害怕“坏用户”,试图破解我的系统修改客户端,如下所示:

const newUserData = {
    name, // I validate type and format in the server
    username,  // I validate type and format in the server
    gender,  // I validate type and format in the server
    avatar,  // I validate type and format in the server
    totalFollowers: 4022348978890, <------- Unexpected field on the server side...
    premium: true <------- Unexpected field on the server side...
} 

然后,如果我在服务器中获取此对象并更新数据库,则该用户将是著名的和优质的。

在服务器端,我只期望字段“名称”、“用户名”、“性别”和“头像”。

如果对象“newUserData”有其他意外字段,我如何签入 Node.js?

注意:我正在寻找一种通用的方法,因为黑客可以在客户端添加他/她想要的字段。

标签: javascript

解决方案


无论用户通过编辑 api 请求参数发送数据,只要您只访问和定位特定属性,这些参数在服务器端都不会产生任何影响。例如,如果我只想要服务器上的用户名、电子邮件或密码,那么显然我只会从 API 请求参数中获取这 3 个值,而不关心其余参数。可能是我编辑了请求并添加了 100 个其他参数,这些参数只会发送到服务器,但由于您仅从请求对象访问 3 个值,因此所有其他参数都将被忽略。但是,不需要实现复杂的逻辑,您可以为此使用以下简单的伪代码逻辑。

const allowed_params = ['username','email','password']
foreach(param in request.params){
 if(param in allowed_params){
    //this is only that is allowed
 }else{
   //just ignore this
 }

推荐阅读