HTTP 400响应安全性的最佳实践



例如,我们有REST端点(甚至是简单端点(。有人传递了不正确的有效载荷,并收到了400个错误代码作为响应。

从安全角度来看,如果某个字段超出了预期长度,应如何详细响应?我们是否应该向用户打开验证详细信息,并在消息字段中返回类似这样的信息:"您超出了邮政编码的长度。最大值为5。"还是应该对用户隐藏详细信息,HTTP状态代码就足够了?

  • 客户端上使用方便的验证消息,如"邮政编码必须有5个数字">
  • 服务器端上,用空400响应

https://cheatsheetseries.owasp.org/cheatsheets/REstrongecurity_Cheat_Sheet.html#error-处理

例如:

const AuthError = 1
const ValidationError = 2
const isId = value =>
isString(value)
&& value.length === StandardIdCharLength
&& /^[w-]*$/.test(value)
async function resetPasswordPost(request, response) {
try {
const body = await jsonBody(request) // throws ValidationError
if (!(
body
&& Object.keys(body).length === 3
&& isPassword(body.password)
&& isId(body.userId)
&& isId(body.token)
))
throw ValidationError
if (!await passwordResetTokenExists(body.token, body.userId))
throw AuthError
// …
sendOk(response)
}
catch (error) {
switch (error) {
case AuthError:
sendUnauthorized(response)
break
case ValidationError:
sendBadRequest(response)
break
default:
sendInternalServerError(response)
}
}
}
function sendBadRequest(response) {
response.statusCode = 400
response.end()
}

最新更新