LoginSignup
0
0

More than 1 year has passed since last update.

Basic認証の導入(健忘録)

Last updated at Posted at 2022-09-09

RailsのAppにBasic認証を導入する

全てのコントローラーで行いたいため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

(補足) 環境変数の設定

vimコマンドで設定ファイルの.zshrcに記述する

ターミナル
% vim ~/.zshrc

通常モードのコマンド

コマンド 説明
:w 作成・編集したファイルを保存
:q vimを終了
:q! 編集した内容を保存しないでvimを強制終了
:wq 編集した内容を保存してvimを強制終了

[i]キーで「insertモード」 ファイルに編集を加えることができる
[Esc]キーで通常モードに戻る

ターミナル
% source ~/.zshrc  
   # sourceコマンドで設定を実行

Heroku上で環境変数を設定

ターミナル
% heroku config:set BASIC_AUTH_USER="「ユーザー名」"
% heroku config:set BASIC_AUTH_PASSWORD="「パスワード」"
0
0
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
0
0