LoginSignup
8
9

More than 3 years have passed since last update.

Basic認証をかけたRailsプロジェクトで特定のURLのみBasic認証をかけない方法

Last updated at Posted at 2016-02-24

ステージング環境とかでベーシック認証を書ける場合は設定ファイル
config/environment/staging.rb に以下のように設定したりする

  config.middleware.use Rack::Auth::Basic do |username, password|
    username == "YOUR_NAME" && password == "PASSWORD"
  end

ここで、特定のURLのみBasic認証を使わずにアクセスしたい場合はRack::Auth::Basicを拡張する必要がある。

いくつか書き方はあるが、以下の条件を満たすようにする

  • staging環境のみ有効にする
  • 特定のURLを正規表現でマッチするものはBasic認証をかけ無いようにする
  • 拡張するクラスのファイルはconfig.ru等に書かずにlibディレクトリ以下に設置した別ファイルとする

libディレクトリの自動読込させる

libディレクトリ以下を自動で読み込ませたい場合は以下のように設定する
こうしておくとlibディレクトリ以下のクラスをいちいち読み込まなくて良いので楽
(各自の方式によっては読み込ませておく必要はない)

config/application.rb

module YourApp
  class Application < Rails::Application
    # libディレクトリ以下のファイルを読み込む
    # Rails4の場合
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    # Rails5またはRails6の場合
    config.eager_load_paths << Rails.root.join("lib")
  end
end

Rack::Auth::Basic拡張クラスの作成

lib/my_basic_auth.rbに以下のようなBasic認証用のクラスを拡張したファイルを作成する

class MyBasicAuth < Rack::Auth::Basic
  def call(env)
    request = Rack::Request.new(env)
    # match の正規表現でヒットするものはbasic認証しない
    if request.path.match(/^\/.well-known/)
      # basic認証をパス
      @app.call(env)
    else
      # basic認証実行
      super
    end
  end
end

Staging環境用の設定ファイルにカスタムBasic認証を読みこませる

※ 適宜production.rb等に読み替える
config/environment/staging.rb

Rails.application.configure do
  # MyBasicAuthを読みこませる"
  config.middleware.use MyBasicAuth do |username, password|
    username == "YOUR_NAME" && password == "PASSWORD"
  end

  # 以下省略
end

refs:
http://stackoverflow.com/questions/6049414/selectively-allow-some-urls-through-rackauthbasic
http://stackoverflow.com/questions/22336048/staging-env-password-protect-everything-except-for-webhook

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9