【问题标题】:Rails - authenticate_or_request_with_http_basic custom "access denied" messageRails - authenticate_or_request_with_http_basic 自定义“拒绝访问”消息
【发布时间】:2009-11-16 23:06:56
【问题描述】:

一旦您使用authenticate_or_request_with_http_basic 在rails 上插入无效凭据作为用户名:密码,我正在努力尝试更改该默认消息。

例如,如果我对需要此身份验证的方法发出 curl 请求,一旦我插入错误的用户名和密码,它就会返回 HTTP Basic: Access denied.

因此,在这种情况下,我希望能够使用特定的 XML 格式字符串自定义此消息(就像 twitter API 一样)。这可能吗?

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby basic-authentication access-denied


    【解决方案1】:

    如果要自定义登录提示中的消息,只需将消息传递给方法调用即可。

    authenticate_or_request_with_http_basic "My custom message" do |user_name, password|
      user_name == USER_NAME && password == PASSWORD
    end
    

    如果你想自定义最终的错误信息,根据 Rails 2.3.4 源代码你可以只为 HTTP Digest 身份验证这样做。

    def authentication_request(controller, realm, message = nil)
      message ||= "HTTP Digest: Access denied.\n"
      authentication_header(controller, realm)
      controller.__send__ :render, :text => message, :status => :unauthorized
    end
    

    基本身份验证将错误消息硬编码到方法中。

    def authentication_request(controller, realm)
      controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
      controller.__send__ :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized
    end
    

    【讨论】:

    • 谢谢 weppos,我之前也检查过,但在这种情况下,我使用 BCrypt 作为密码加密,所以我不确定是否可以使用 Http Digest Auth有了它,另一件事是,有没有办法从 http basic 覆盖这个函数?我尝试了但没有成功,因为这有点奇怪,因为 Twitter API 似乎也使用了 Http Basic,并且他们能够配置最终的错误消息。
    • 是的,通过猴子补丁你可以覆盖几乎所有东西......但这并不总是一个好主意。
    猜你喜欢
    • 2018-11-30
    • 2016-07-28
    • 2021-09-17
    • 1970-01-01
    • 2015-07-06
    • 2012-04-10
    • 2012-02-22
    相关资源
    最近更新 更多