加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 21:25:18 所属栏目:百科 来源:网络整理
导读:我想在登台服务器上实现HTTP基本身份验证,但仅适用于本地网络之外的身份验证.我有一个Rails 3.1应用程序.在application.rb中,我有以下内容: class ApplicationController ActionController::Base http_basic_authenticate_with :realm = "Staging",:name =
我想在登台服务器上实现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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读