ROR – HTTP基本身份验证

参考<Rails 高级编程> Page100

module Backend
  class BaseController < ActionController::Base
    before_action :authenticate

    private

    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
        username == "#{Rails.application.secrets[:name]}" && password == "#{Rails.application.secrets[:password]}"
      end
    end
  end
end

另外一种写法:

module Backend
  class BaseController < ActionController::Base
    http_basic_authenticate_with name: "#{Rails.application.secrets[:name]}", 
      password: "#{Rails.application.secrets[:password]}", if: :need_authentication?

    private

      def need_authentication?
        !Rails.env.development?
      end
  end
end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 最近在 Ruby China 看到 @huacnlee 分享的 The Rails Doctrine - 中文翻译...
    freefishz2阅读 4,707评论 0 6
  • 阅读Tips: 本文是我根据这么多年来的实际开发、技术管理经验的一些总结,完整阅读需要30分钟,已经整理成简书专题...
    hirainchen阅读 12,691评论 12 118
  • 1.caching with instance variables2.dynamic find_by method...
    Jayzen阅读 5,262评论 0 1
  • 北京八达岭野生动物园,一名年轻的女子与丈夫斗气,在猛兽区自驾游时擅自下车,被老虎袭击拖走,其母亲不惧猛兽威胁,不顾...
    酱油君阿爸阅读 2,394评论 0 2
  • 奥巴马给女儿的一封信,这是我看过最好的心灵鸡汤 我的生活影像之旅 百家号16-12-13 21:10 关注 奥巴马...
    风过留香_3356阅读 1,020评论 0 0