自定义401页面,authenticate_or_request_with_http_digest失败-rails 4



我在rails 4中使用authenticate_or_request_with_http_digest方法,让管理员登录并执行一些简单的任务。底部的所有链接和来源。

application_controller.rb

before_action :authenticate, only: :index # etc
def authenticate
   authenticate_or_request_with_http_digest(CONFIG[:realm]) do |username|
     session[:admin] = username
     USERS[username]
   end
 end

这正如预期的那样,然而,当用户取消登录过程时呈现的默认401页面非常糟糕,它是一个带有一些文本的空白页面。我使用的是Railscasts.com EP#53中的自定义错误模板,如果我能对这个401错误使用相同的约定,那就太好了。

有没有一种方法可以修改下面的方法以显示自定义401页面(最好不包括所有的控制器视图和url帮助程序),或者有一种更简单的方法来实现动态401页面?

ActionController::HttpAuthentication::Digest.module_eval do
  def authentication_request(controller, realm, message = nil)
    message ||= "You are unauthorized to access this page.n"
    authentication_header(controller, realm)
    controller.response_body = message
    controller.status = 401
  end
end

来源

Railscasts EP#53自定义错误模板:http://railscasts.com/episodes/53-handling-exceptions-revised-

似乎控制401处理的authenticate_request方法,完整来源如下:https://github.com/rails/rails/blob/04cda1848cb847c2bdad0bfc12160dc8d5547775/actionpack/lib/action_controller/metal/http_authentication.rb#L244

这里可以看到authenticate_or_request_with_http_digest方法和示例:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Digest.html#method-i-authentication_request。

感谢这篇关于该主题的精彩博客文章,下面的代码优雅地呈现了errors/401模板。(最好清理以使用super,而不是不推荐使用的alias_chaining方法)

config/ininitializers/authentication.rb

ActionController::HttpAuthentication::Digest.module_eval do
  def authentication_request_with_customization(controller, realm, message = nil)
    message = controller.render_to_string(template: "errors/401")
    authentication_request_without_customization(controller, realm, message)
  end
  alias_method_chain :authentication_request, :customization
end

原始帖子:http://p373.net/2013/11/16/how-to-customize-http-digest-authentication-error-pages-in-ruby-on-rails/

最新更新