【问题标题】:Devise authentication when accessing directly to a pdf file unauthenticated在直接访问未经身份验证的 pdf 文件时设计身份验证
【发布时间】:2011-11-03 14:41:47
【问题描述】:

当我试图查看未经身份验证的 .pdf 文件(使用 PDFKit 生成)时,我遇到了一个问题,它直接来自给定的 URL host/.../profile.pdf。正如预期的那样,我被要求输入如图所示的凭据(不在 users/sign_in 路径中):

我输入了正确的凭据,框上下移动并再次询问凭据。看起来用户名或密码错误,但事实并非如此。控制器的相关代码在这里:

class Entrepreneur::ProfilesController < ApplicationController
  before_filter :authenticate_user!

  def show
    respond_to do |format|
      format.pdf do
        html = render_to_string(:layout => false , :action => "show.html.haml")
        kit = PDFKit.new(html)
        send_data(kit.to_pdf, :filename => "name.pdf", :type => 'application/pdf')
      end
    end
  end
end

如您所见,没有什么花哨的。我试图从过滤器 (before_filter :authenticate_user!, :except =&gt; [:show]) 中删除显示操作并为自己编写一个自定义过滤器以将未经身份验证的用户重定向到 new_session_path,但是这样做我不知道如何在注册后将用户重定向到 pdf 节目.

简而言之,devise 在访问 pdf 节目时会询问我的凭据,但不接受这些凭据。如何让用户进入登录页面并在签名后重定向回 pdf?

我正在使用 Rails 3.0.7、Ruby 1.8.7 和 Devise 1.1.5。

谢谢!

【问题讨论】:

  • 为什么会弹出一个框? before_filter :authenticate_user! 应该将您重定向到登录页面,不是吗?你有什么改变吗?
  • 您需要显示验证用户身份的代码。
  • @Robin,不,没有任何改变
  • @draevor,Devise 负责处理,我没有更改 devise 的功能。
  • @Robin,是的,它应该在任何其他情况下都会这样做,但在直接访问 PDF 时不会。

标签: ruby-on-rails devise


【解决方案1】:

首先,确保它实际上是在为 PDF 提供服务的 Rails,而不是它前面的 Web 服务器。 (根据您的配置,请求可能一开始就没有到达 Rails。)

假设它是 Rails 提供的文件,那么你应该检查你的 devise.rb 配置文件。您可能需要将 :pdf 设为一种导航格式,以便 Devise 向您的登录页面发出 302 重定向:

config.navigational_formats = [:html, :pdf] # you may have additional formats

此外,您可能需要将 PDF 添加到您的 mime_types.rb 初始化程序(如果它还没有的话):

Mime::Type.register 'application/pdf', :pdf

【讨论】:

  • 谢谢克里斯! Rails 实际上是在提供(或尝试提供)PDF,并将 pdf 添加到设计 navigational_formats 工作!很高兴知道:D(我还需要 3 个小时来奖励赏金)
  • 谢谢!这解决了我的问题!但是,现在设计将我重定向到 /users/sign_in.pdf。有什么办法可以将 .pdf 从登录路径中删除?
  • 好吧,我找到了解决我自己问题的方法:覆盖skip_format? custom_failure.rb 中的方法(/).include? request_format.to_s
【解决方案2】:

添加到接受的答案并重复完整性:

更新您的设计配置 (config/initializers/devise.rb) 以将 pdf 包含为 navigational_format

同时更新您的设计配置以使用自定义 failure_app

require 'custom_failure'

Devise.setup do |config|
  # Navigate on pdf request types (i.e. .pdf)
  config.navigational_formats = ["*/*", :html, :pdf]

  config.warden do |manager|
    # Custom app to redirect to login page on unauthenticated pdf request types
    manager.failure_app = CustomFailure
  end
end

自定义故障应用 (lib/custom_failure.rb)

class CustomFailure < Devise::FailureApp

  # Redirect pdf request types to the login page
  def skip_format?
    %w(html pdf */*).include? request_format.to_s
  end

end

【讨论】:

  • 这是完美的答案,对我很有用。
猜你喜欢
  • 1970-01-01
  • 2019-01-29
  • 2020-08-25
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 2019-06-14
  • 2018-01-05
  • 2016-11-04
相关资源
最近更新 更多