【问题标题】:Rails 5.2: authorize access to ActiveStorage::BlobsController#showRails 5.2:授权访问 ActiveStorage::BlobsController#show
【发布时间】:2019-10-23 06:53:53
【问题描述】:

我想授权访问ActiveStorage附件并查看BlobsControllerhttps://github.com/rails/rails/blob/master/activestorage/app/controllers/active_storage/blobs_controller.rb)的源代码如下:

# Take a signed permanent reference for a blob and turn it into an expiring service URL for download.
# Note: These URLs are publicly accessible. If you need to enforce access protection beyond the
# security-through-obscurity factor of the signed blob references, you'll need to implement your own
# authenticated redirection controller.
class ActiveStorage::BlobsController < ActiveStorage::BaseController
  include ActiveStorage::SetBlob

  def show
    expires_in ActiveStorage.service_urls_expire_in
    redirect_to @blob.service_url(disposition: params[:disposition])
  end
end

但即使上面的注释建议创建一个自定义控制器,我也需要覆盖 ActiveStorage 生成的路由,因为它们指向原始控制器,并且在我的 routes.rb 上重新定义它们似乎会引发异常。此外,我不想再公开这些路由,因为它们没有被授权,有人可以获取 blob 的 signed_id 并使用原始端点获取附件。 在应用程序初始化时循环遍历路由并删除旧的 ActiveStorage 路由并插入新的路由似乎是目前最好的解决方案,但我想避免这种情况。

有什么建议吗? ????

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    创建一个新的控制器来覆盖原来的:app/controllers/active_storage/blobs_controller.rb,然后根据您的需要添加相应的授权方法:

    #app/controllers/active_storage/blobs_controller.rb
    class ActiveStorage::BlobsController < ActiveStorage::BaseController
      include ActiveStorage::SetBlob
    
      def show
        redirect_to @blob.service_url(disposition: params[:disposition])
        authorize! :show, @blob # NOT TESTED!
      end
    
    end
    

    当您点击附件的链接时会触发show 操作。

    @blob.class #=> ActiveStorage::Blob
    

    【讨论】:

    • 只是需要修复,authorize! 应该放在方法的开头或 authorize_resource 在控制器的顶部
    猜你喜欢
    • 2019-05-19
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2018-02-02
    • 2016-10-07
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多