英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论