如何在Rails中拦截"user[comment]"格式的恶意参数提交?
Rails中拦截"user[comment]"这类非标准参数提交的方法
使用强参数(Strong Parameters)严格限定允许的参数
Rails的强参数机制本身就能有效过滤非法参数。在控制器中明确指定允许的嵌套参数结构:def user_params params.require(:user).permit(:comment, :other_allowed_field) end当提交的是字符串形式的
"user[comment]"而非嵌套的:user哈希时,params.require(:user)会直接抛出ActionController::ParameterMissing异常,非法请求会被自动拦截。自定义全局参数过滤中间件
如果需要在全局范围内拦截这类非法参数,可以编写一个Rails中间件:class InvalidParamFilter def initialize(app) @app = app end def call(env) request = ActionDispatch::Request.new(env) # 筛选出以"[xxx]"结尾的非法参数键 invalid_keys = request.params.keys.select { |key| key =~ /\[\w+\]$/ } unless invalid_keys.empty? return [400, {'Content-Type' => 'text/plain'}, ['Invalid parameter format']] end @app.call(env) end end然后将该中间件添加到
config/application.rb的中间件栈中:config.middleware.use InvalidParamFilter通过路由约束限制参数格式
针对特定路由,可添加自定义约束,仅接受符合嵌套哈希结构的参数:class ValidParamConstraint def matches?(request) request.params.key?(:user) && request.params[:user].is_a?(Hash) end end Rails.application.routes.draw do post '/users', to: 'users#create', constraints: ValidParamConstraint.new end不符合约束的请求会直接返回404,无法进入控制器处理逻辑。
控制器层提前校验参数结构
在对应action的开头直接校验参数结构:def create unless params[:user].is_a?(Hash) render status: :bad_request, plain: 'Invalid parameter structure' return end # 后续正常业务逻辑 end
内容的提问来源于stack exchange,提问作者Jerome
相关产品推荐
相关产品推荐

