LoginSignup
0
0

More than 1 year has passed since last update.

Rails Basic認証の導入

Posted at

Basic認証とは、HTTP通信の規格に備え付けられている、ユーザー認証の仕組み。
ブラウザ開いたらidとパスワードが求められるやつですね。

これはもう単純なんでコードをバシバシ記述していきます。
基本コピペで大丈夫

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 == '自分の好きな名前' && password == '自分の好きなpass'
    end
  end
end

これで導入自体は出来てますが、しかしながらこれではあまりBasic認証を導入するメリットがありませんね?
何故ならコードを見れば、丸わかりだから。
Basic認証なんてセキュリティ上の問題で設定するのであって、これではまるで意味ないですね。
ということで、環境変数を使用しましょう。

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

ターミナルで上記キーを実行して、「iキー」を押して、インサートモードに移行

export BASIC_AUTH_USER='ユーザー名'
export BASIC_AUTH_PASSWORD='パスワード'

記述を追加したら「escキー」を押して、 「:wq」と入力
エンターを押す

source ~/.zshrc

Herokuにデプロイしている場合は

heroku config:set BASIC_AUTH_USER="ユーザー名"
heroku config:set BASIC_AUTH_PASSWORD="パスワード"
git add .
git commit -m "自分で決めてください。"
git push heroku master

これで完了です。

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