これは何
Railsでベーシック認証を実装する方法
やり方
2つのやり方がある
1. authenticate_or_request_with_http_basicを使うやり方
2. http_basic_authenticate_withを使うやり方
1. authenticate_or_request_with_http_basicを使うやり方
1 2 3 4 5 6 7 8 9 10 |
class HogeController < ApplicationController before_action :basic_authenticate def basic_authenticate # ApplicationControllerのものと揃える authenticate_or_request_with_http_basic do |name, password| name == 'name' && password == 'password' end end end |
たったこれだけでHogeController内の処理に対してベーシック認証をかけられる。
全体にかけたいなら、ApplicationController内に書いたり、特定のアクションにだけかけたいならonly: [:poyo]とかつければ良い。
2. http_basic_authenticate_withを使うやり方
1 2 3 |
class HogeController < ApplicationController http_basic_authenticate_with name: 'name', password: 'password' end |
これでも同様にベーシック認証をかけられる。
実は後ろにオプションを渡せて、
http_basic_authenticate_with name: ‘name’, password: ‘password’, only: :puyo
とか
http_basic_authenticate_with name: ‘name’, password: ‘password’, except: :puyo
もできる。
まとめ
・どちらでのやり方も似たようなことができる
・nignxなどのWebサーバの設定をいじらなくてもRailsのレイヤーでベーシック認証をかけることができるのでお手軽感
参考
https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html