find_by_id sql 在 rails 中注射安全吗?
is find_by_id sql injection safe in rails?
我的 rails 控制器中有以下代码:
State.find_by_id(params[id])
这里的参数[id]是用户输入
我是否需要清理此参数以使上述调用免受 SQL 注入的影响?
是的,这个方法ActiveRecord::FinderMethods而且安全。
小例子:
User.find_by_id("' OR 1 --")
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT 1 [["id", 0]]
=> nil
find_by
已经清理参数。
find_by_id
使用to_i,所以这里不能使用字符串。
Person.find_by_id('any string')
将与 Person.find_by_id(0)
相同。
Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
is an integer, find by id coerces its arguments using +to_i+.
Person.find(1) # returns the object for ID = 1
Person.find("1") # returns the object for ID = 1
Person.find("31-sarah") # returns the object for ID = 31
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for the object with ID = 1
Person.where("administrator = 1").order("created_on DESC").find(1)
我的 rails 控制器中有以下代码:
State.find_by_id(params[id])
这里的参数[id]是用户输入
我是否需要清理此参数以使上述调用免受 SQL 注入的影响?
是的,这个方法ActiveRecord::FinderMethods而且安全。
小例子:
User.find_by_id("' OR 1 --")
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT 1 [["id", 0]]
=> nil
find_by
已经清理参数。
find_by_id
使用to_i,所以这里不能使用字符串。
Person.find_by_id('any string')
将与 Person.find_by_id(0)
相同。
Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key is an integer, find by id coerces its arguments using +to_i+.
Person.find(1) # returns the object for ID = 1
Person.find("1") # returns the object for ID = 1
Person.find("31-sarah") # returns the object for ID = 31
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for the object with ID = 1
Person.where("administrator = 1").order("created_on DESC").find(1)