ruby-on-rails - 有条件的HTTP基本身份验证

标签 ruby-on-rails basic-authentication

我想在我的登台服务器上实现HTTP基本身份验证,但仅适用于本地网络之外的服务器。我有一个Rails 3.1应用程序。在application.rb中,我有以下内容:

class ApplicationController << ActionController::Base
  http_basic_authenticate_with :realm => "Staging", :name => "user", :password => "password" if :need_authentication?

private

  def need_authentication?
    Rails.env == "staging" && request.remote_addr !~ /^192.168.0.\d{1,3}$/
  end

end

麻烦之处在于:即使need_authentication?方法显式返回false,应用程序仍然要求我进行身份验证,好像它完全忽略了最后的if子句。

那么,有什么方法只需要在特定条件下进行身份验证吗?

最佳答案

在Rails 4中,:if条件起作用。例如,

class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password" if Rails.env == 'staging'
end

或者,如果您希望使用辅助方法设置条件,
class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password", if: :need_authentication?

  private
  def need_authentication?
    Rails.env == 'staging'
  end
end

关于ruby-on-rails - 有条件的HTTP基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7972934/

相关文章:

ruby-on-rails - Ruby:只列出 id 不包含在另一个表中的项目

ruby-on-rails - 如何在 Rails 中设置 GraphQL Relay API

ruby-on-rails - 作为 Rails 3.0 的核心堆栈,我能期待什么?我现在需要将什么作为插件包含在内

c# - C#HTTPWebRequest与领域网站进行协商/基本

spring-security - Spring OAuth2 授权服务器,带有通过基本身份验证保护的执行器端点

ruby-on-rails - 与 Rails 应用程序进行 pubnub 聊天的数据持久性

ruby-on-rails - rails : Cleaning up large methods in controllers

cocoa 基本 HTTP 身份验证 : Advice Needed

javascript - Firefox 删除基本授权信息

使用基本身份验证加载 UIWebView 资源