LoginSignup
10

More than 5 years have passed since last update.

Ruby on RailsでDeviseを用いてセキュアな認証機能を作る

Last updated at Posted at 2015-09-08

課題

ログイン認証の際にRuby on RailsのDeviseを使っている。
セキュリティ強化のために複数回ログイン失敗した際にアカウントのロックを行いたい。
(今回はUsersテーブルの変更を意図して行っている。)

対応

①ログイン対象のテーブルにカラムを追加する。
②モデルの内容を変更する。
③Deviseの設定を変更する。

① ログイン対象のテーブルにカラムを追加する。

 rails g migration AddLockableColumsToUsers failed_attempts:integer unlock_token:string locked_at:datetime

faliled_attemptsに default: 0, null: false を追加
migration fileは以下のようになる。

 1 class AddLockableColumsToUsers < ActiveRecord::Migration
 2   def change
 3     add_column :users, :failed_attempts, :integer, default: 0, null: false                                                                                                    
 4     add_column :users, :unlock_token, :string
 5     add_column :users, :locked_at, :datetime
 6   end
 7 end

② モデルの内容を変更する。

対象のモデルのdeviseの設定にlockableの内容を追記する

app/models/xxx.rb

devise :database_authenticatble,xxxxxxxxxxxxxx, xxxxx...., :lockable

③ Deviseの設定を変更する。

config/initializers/devise.rb に以下の設定を追加

 config.lock_strategy = :failed_attempts # 一定回数ログインミスでロック
 config.unlock_strategy = :time          # ロック解除条件は時間経過のみ
 config.maximum_attempts = 5             # 5回連続ミスでロック
 config.unlock_in = 1.hour               # 1時間ロック継続
 config.last_attempt_warning = false     # 残りミス回数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
10