我们应该在API中验证路径参数吗?

huangapple go评论79阅读模式
英文:

Should we validate path parameters in API?

问题

我有一个API /api/examples/:id,其中id整数的形式存储在数据库中。对于验证错误,我返回400,对于未找到的资源,我返回404。

在这个API中,我需要验证id的数据类型吗?(当客户端将id参数传递为字符串,例如/api/examples/abc时,我应该返回400还是404?)。

英文:

I have an API /api/examples/:id and id is stored in database as Integer. I also return 400 for validation error and 404 for resource not found.

Should I need to validate id data type in this API ? (Should I return 400 or 404 when client pass id param as String like /api/examples/abc ?).

答案1

得分: 1

我猜你是在使用它进行数据库查询。所以你应该确保在将API参数传递到SQL语句中时,没有发生SQL注入。

你可以通过检查id是否为整数来进行检查。或者你可以使用mysql驱动程序的功能,使用?作为参数,这样它会检查语句是否有效,不会破坏查询。

事实上,无论如何你都应该这样做。

如果你只是将id作为不安全的字符串进行传递,并且没有使用正确的SQL功能,而是将字符串附加到查询中并执行...你可能会成为SQL注入攻击的目标。所以是的,你应该检查输入或者使用正确的mysql驱动程序函数来确保安全!

英文:

I suppose you make a database query with it. So you should definetely check the input that no SQLInjection happens when forwarding the API parameter into your SQL-Statement.

You can do the check yourself by checking that id is an integer. Or you can use the mysql Driver capabilities to use parameters with ? so it checks that the statement is valid and not breaking the query.

In fact you should do this anyhow.

If you just forward the id as a unsafe-string and do not use the correct sql capabilities but just append strings to a query and execute... you might be targetd by SQLInjection attacks. So yeah, either you should check the input or use the correct mysql driver functions to be safe here!

huangapple
  • 本文由 发表于 2023年5月10日 11:31:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76214712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定