LoginSignup
1
1

More than 1 year has passed since last update.

Basic認証

Last updated at Posted at 2022-11-17

ユーザー認証を導入

開発環境で環境変数を設定

※macOSがCatalina以降の場合

たとえば

「xxxx」というユーザー名と
「0000」というパスワードにて、設定をする場合。

①ターミナルで以下を実行する
ターミナル
vim ~/.zshrc

すると、「~」が縦に大量に表示される。

②「i」を押下し「インサートモード」にする

「-- INSERT --」と最下部に表示される。

③zshの内部に、以下の記述を追加
ターミナル
export BASIC_AUTH_USER='xxxx'
export BASIC_AUTH_PASSWORD='0000'
~
~
~
~
-- INSERT --
④インサートモードを終了

「escキー」→ 「:wq」→「Enterキー」を押して終了。

⑤sourceコマンドを実行
ターミナル
source ~/.bash_profile
⑥環境変数をRailsアプリケーション側で読み込む

「app/controllers/application_controller.rb」を以下のように記述。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :basic_auth


  private

  def basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV["BASIC_AUTH_USER"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end
end

本番環境で環境変数を設定

①ダッシュボードを開き該当するアプリ名をクリック
②「Environment」をクリックし以下のように環境変数を設定

Key Value
BASIC_AUTH_PASSWORD 0000
BASIC_AUTH_USER xxxx

#techcamp136期

1
1
1

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
1
1