【问题标题】:Rails: How to produce 404 or redirect upon undesired url exploitation?Rails:如何产生 404 或重定向不受欢迎的 url 漏洞?
【发布时间】:2011-02-07 16:32:09
【问题描述】:

我想将用于编辑用户及其个人资料的 url 隐藏在更安全、更有意义的 url 后面。例如,我希望/user/13/edit 成为/settings/account/user/13/profile/edit 成为/settings/profile

我设法实现了这一点,但为此我必须从会话的current_user 位加载用户信息。像这样:

# users_controller
def edit
  @user = current_user
end

# profiles_controller
def edit
  @user = current_user
  @profile = @user.profile
end

但是现在,由于我无法将来自params@user.id 与会话中的current_user 进行比较,我如何才能阻止旧网址(/user/13/edit/user/13/profile/edit)被利用?他们总是为当前用户加载表单,所以不会造成任何伤害,但如果他们只是产生 404 错误或其他什么,我会更舒服。

提前致谢。

【问题讨论】:

    标签: ruby-on-rails redirect routing http-status-code-404


    【解决方案1】:

    首先,你的认证机制需要设置当前用户。

    routes.rb

    map.account '/settings/account', :controller => 'user', :action => 'edit' 
    map.profile '/settings/profile', :controller => 'user', :action => 'edit_profile'
    
    map.resources :users, :only => [:edit, :update, :show],
                  :member => { :edit_profile => :get, :update_profile, :put }
    

    这会产生以下路线:

    /settings/account         (get)
    /settings/profile         (get)
    /users/:id                (get, put)
    /users/:id/edit           (get)
    /users/:id/edit_profile   (get)
    /users/:id/update_profile (put)
    

    users_controller.rb

    before_filter :redirect_if_unauthorized
    
    def edit
      @user = current_user
    end
    
    # profiles_controller
    def edit
      @user = current_user
      @profile = @user.profile
    end
    
    protected
    
    def redirect_if_unauthorized
      redirect_to some_path if params[:id] or current_user.nil?
    end
    

    显然 some_path 不存在,您必须创建页面/路径等才能显示错误。

    使用此解决方案,您永远不会根据 params[:id] 显示/操作用户,而只会显示/操作您的身份验证方案保存的 current_user。


    我可能还建议查看 declarative_authorization gem/plugin (Github, Railscast)

    【讨论】:

    • 我的问题恰恰是新的 url 不提供我可以用来比较的参数了。
    • 我做了一些修改,是不是更接近你要找的东西?
    • 我尝试根据我的代码调整您的解决方案,但无法使其正常工作。我现在要研究插件。感谢您的帮助。
    • 很高兴,告诉我进展如何。顺便问一下,您在使用此解决方案时遇到的具体问题是什么?
    【解决方案2】:

    /edit url 仍然存在,因为我打赌你的 routes.rb 文件中有一个 map.resources 用于用户模型。您可以在您的 routes.rb 文件中放置比该行更高的行,该行明确匹配您要重新路由的编辑行并将它们指向您想要的任何位置。

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多