Rails – authenticate_or_request_with_http_basic自定义“访问被拒绝”消息

在使用authenticate_or_request_with_http_basic在rails上插入无效凭据作为username:password时,我正在努力尝试更改默认消息。

例如,如果我对需要此身份validation的方法发出curl请求,则在插入错误的用户名和密码后,它将返回HTTP Basic: Access denied.

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

提前致谢

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

 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摘要进行身份validation。

 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 

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

 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 
Interesting Posts