gpt4 book ai didi

rails-activestorage - 如何为 ActiveStorage 添加权限?

转载 作者:行者123 更新时间:2023-12-05 02:11:34 28 4
gpt4 key购买 nike

我正在将一个权限敏感的应用程序迁移到 ActiveStorage。我需要确保文件只能由具有权限的人访问,并且这些权限只能持续指定的时间段。

使用 Paperclip,这就像使用专家授权调用定义路由一样简单:

def thumbnail
authorize @record
redirect_to @record.thumbnail.expiring_url(300)
end

任何对 /record/thumbnail 的调用都将由 devise 进行身份验证,由 pundit 授权,然后使用过期 url 重定向到 S3。这是一个有效的过程。

转向 ActiveStorage,我最初的想法是我会使用 service_url,但它只在我使用 S3 时有效——它在测试中不起作用,它在以下情况下不起作用我正在使用磁盘服务进行本地开发。实际的“正确”方法是使用 url_for,或者在上面的示例中使用 redirect_to url_for @record.thumbnail

问题是,url_for 似乎发布了一个永久 url -- 它生成的 url 对任何人都始终有效,无需身份验证或授权。更重要的是,一旦有人拥有那个 url,我就无法撤销它,我不能说它只能用一周。一旦有人拥有该 url,他们就可以永远访问该文件。 (或者,大概,至少在文件更新之前)。

我不认为这是一个巨大的安全漏洞,但与使用 Paperclip 可实现的功能相比,这绝对是倒退了一步。我是否遗漏了一个重要的细节,或者这真的是 ActiveStorage 所能做到的一切吗?

最佳答案

文档说:

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.

这不是特别有用。为此,您需要创建自己的 Controller 来为 blob 提供服务:

class BlobsController < ApplicationController
include ActiveStorage::SetBlob
before_action :authorize_blob

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

private

def authorize_blob
# Your authorization code goes here
end
end

然后您需要设置路由:

  get '/blobs/:signed_id/*filename' => "blobs#show", as: "service_blob"
direct :blob do |blob, options|
route_for(:service_blob, blob.signed_id, blob.filename, options)
end
resolve("ActiveStorage::Blob") { |blob, options| route_for(:blob, blob, options) }

最后,您需要禁用不安全的默认 Controller ,以便知识渊博的用户无法规避您的授权。

如果您使用的是 Rails 6.1+,您可以通过在 application.rb 中将 config.active_storage.draw_routes 设置为 false 来实现。但是您需要确保其余的 ActiveStorage 路由是手动绘制的,并且其中有很多。你可以view them on Github .

否则,您将需要添加扩展 Controller 以重定向到您的新 Controller (或者完全关闭它)。您可以将以下内容添加到初始化程序中:

module ActiveStorageRedirect
def self.included(controller)
controller.before_action :redirect_to_authenticated
end

private

def redirect_to_authenticated
redirect_to Rails.application.routes.url_helpers.blob_path(@blob)
end
end

ActiveStorage::Blobs::RedirectController.include(ActiveStorageRedirect) # For Rails >= 6.1
ActiveStorage::Blobs::ProxyController.include(ActiveStorageRedirect) # For Rails >= 6.1
# ActiveStorage::BlobsController.include(ActiveStorageRedirect) # For Rails < 6.1

关于rails-activestorage - 如何为 ActiveStorage 添加权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369700/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com