【问题标题】:how do i restrict access to file URLs如何限制对文件 URL 的访问
【发布时间】:2014-08-29 10:55:08
【问题描述】:

我想限制访问的网络服务器上的一些文件。 例如 www.example.com/privatefiles/secret.txt

我试过这个:

routes.rb:

get '/privatefiles/:file.:ext' => 'file_handler#authenticate'
#.......

file_handler_controller.rb:

class FileHandlerController < ApplicationController
     def authenticate
         if(session[:user_id] == ADMIN)
             sendfile
         else
             redirect_to '/NO'
         end
     end
end

我发现当我输入 不存在 的文件的 URL 时,它的行为正确,但是当文件存在时,路由会被忽略,浏览器将直接转到该文件,并且甚至从未到达控制器

【问题讨论】:

  • 为了限制对文件的访问,我通常宁愿将它们放在我的 web 根目录之外,并通过特定的处理程序访问它,您还可以在其中进行其他类型的检查,而不仅仅是基本的用户身份验证(例如:记录下载,限制访问次数,...)

标签: ruby-on-rails ruby-on-rails-4 routes


【解决方案1】:

尝试这样做

在路线中:

get '/privatefiles/:file.:ext' => 'file_handler#fetch_file'

在您的控制器中:

class FileHandlerController < ApplicationController

  before_filter :authenticate

  def fetch_file
    # send/ show file code here
    sendfile
  end

  private

  def authenticate
    unless (session[:user_id] == ADMIN)
      redirect_to root_path, :notice => 'Doing something nasty, huh?'
    end
  end
end

【讨论】:

  • 仍然绕过控制器。 Rails 中可能存在错误?
  • 不,问题在这里:(session[:user_id] == ADMIN) 你如何验证这个条件?
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 2012-11-08
  • 2012-04-03
  • 1970-01-01
  • 2017-05-03
  • 2012-08-28
  • 2019-03-08
  • 2013-01-04
相关资源
最近更新 更多