1.輸入驗證?
對傳遞的數據的格式、長度、類型(前端和后端都要)進行校驗。
對黑白名單校驗:比如前端傳遞了一個用戶名,可以搜索該用戶是否在白名單或者黑名單列表。
針對黑名單校驗,比如:
// 手機號驗證碼登錄的時候,需要check一下手機號
async sendAuthCode(phone){if(!_.isString(v))return falseconst phone = phone.replace(/[a-zA-Z]/gi,'')if(phone.length!==11) return falseconst forbidden = ['170','171','165','167']const isR = forbidden.some(item=>phone.startsWith(item))if(isR)return false
}
2.身份認證與授權?
身份認證(屬于node后端責任),核心思想:后端A向第三方服務B端發起請求的時候在請求頭添加一個3個字段:
projectKey,appKey,authorization,
其中前兩個key是A和B商量好的一串碼(比如dfs3290sdf)
authorization是通過給param參數轉成md5,混合一堆content-type,uri之類的配合B提供的密鑰secretKey進行hmac編碼,生成簽名signature。
然后B端根據相反的規則解析這三個字段,與自己手上的projectKey,appKey,secretKey進行對比
上代碼:
// 偽代碼const Authorization = this.getAuthorization('POST', reqParams, this.contentType, this.uri, date, this.secretKey, this.accessKey);const headers = {'Content-Type': this.contentType,'Authorization': Authorization,'projectKey': this.projectKey,'appKey': this.appKey,'Date': date,'X-Forwarded-For': '192.168.42.94'}const options = {method: 'POST',headers};
const res = await this.Fetch(url, options, param);getAuthorization(method, params, contentType, uri, date, secretKey, accessKey): string {const md5 = this.getContentMD5(params);const constToSign = method + '\n' + md5 + '\n' + contentType + '\n' + date + '\n' + uri;// 將constToSign施行utf-8轉換const utf8Data = Buffer.from(constToSign, 'utf8');// 使用HMAC-SHA1和密鑰進行編碼const hmac = crypto.createHmac('sha1', secretKey);hmac.update(utf8Data);const encodedData = hmac.digest();// 使用Base64進行最后的編碼const signature = encodedData.toString('base64');return `${accessKey}:${signature}`;}getContentMD5(params) {let contentMD5 = '';const jsonString = qs.stringify(params);contentMD5 = crypto.createHash('md5').update(jsonString).digest('base64')return contentMD5;
}