最近不正ログインについての報道を見るので以前調べた2要素認証の実装について書く。
gem two_factor_authentication
gem deviseのプラグインにgem two_factor_authenticationというのがある。
これはdeviseの認証機構に2要素認証を追加することができるプラグイン。
Houdini / two_factor_authentication
一応deviseのExtensionsにも紹介されている。
実装
Userモデルでユーザー認証を実装している前提での実装方法。
Gemfileに下記を追加。
gem two_factor_authentication
コマンドを実行。
bundle install
bundle exec rails g two_factor_authentication User
bundle exec rake db:migrate
これでログイン時に2要素認証を求められる様になるが、ユーザーは発行された認証コードを知る事が出来ない。
そこで、two_factor_authenticationが用意しているフック用のメソッドsend_two_factor_authentication_code(code)
をUserクラスでオーバーライドする事で認証コードを好きな方法で通知する事が出来る。
登録されたメールに対して通知メールを送信する時は下記。
class User < ActiveRecord::Base
def send_two_factor_authentication_code(code)
UserMailer.two_factor_authentication_code(code).deliver
end
end
蛇足
2要素認証用のmigrateファイルを生成するコマンド
bundle exec rails g two_factor_authentication User
で作成されるmigrateファイルは下記。
class TwoFactorAuthenticationAddToUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.string :second_factor_pass_code , :limit => 32
t.integer :second_factor_attempts_count, :default => 0
end
end
end
second_factor_pass_code
にはハッシュ化された認証コード、second_factor_attempts_count
には認証コードの入力に失敗した回数が書き込まれる。
デフォルトの設定では3度認証に失敗するとログイン出来なくなる。
READMEを読むと細かな設定をする方法が載っている。