回上一頁

Rails7 2FA 驗證api

此篇使用以下gem:

gem 'google-authenticator-rails' 

bundle install

 

在desive user model裡面加以下: 

acts_as_google_authenticated lookup_token: :mfa_secret, encrypt_secrets: true 

 

在User新增兩個欄位: 

  google_secret:string 

  mfa_secret:integer 


 

登入和註冊時寫在Controller: 

@user = User.new 
@user.set_google_secret           # => true 
@user.google_secret_value         # => 16-character plain-text secret, whatever the name of the secret column 
@user.google_qr_uri               # => http://path.to.chart/qr?with=params 
@user.google_authentic?(123456)   # => true 
@user.clear_google_secret!        # => true 
@user.google_secret_value         # => nil 

 

基本流程: 

1.註冊or登入之後先到 mfa session new 頁面(新開一個頁面) 

  

進行第二次登入,如果第二次登入沒有過關,把你登出掉! 

 

Controller加上: (來源是models的acts_as_google_authenticated 

@user = User.new 
@user.set_google_secret           # => true 
@user.google_secret_value          

# => 16-character plain-text secret, whatever the name of the secret column 
 

@user.google_qr_uri                

# => http://path.to.chart/qr?with=params 
 

@user.google_authentic?(123456)   # => true 
@user.clear_google_secret!        # => true 
@user.google_secret_value         # => nil 

 

2.掃描 qrcode => Google Authenticated (mobile) => 輸入驗證碼(6碼) 

@user.google_authentic?(params[:mfa_secret]) 

 

P.S. View畫面 (QRCODE設置): 

需要開一個第二次登入頁面 new + create routes 

 

@user = User.find(params[:id]) @qr_code_uri = @user.google_qr_uri(@user.email) 

 

<h1>User Settings</h1> 

<p>Scan this QR Code with your Google Authenticator app to set up two-factor authentication:</p>  

<%= image_tag @qr_code_uri, alt: "Google Authenticator QR Code" %> 

 

測試 Rails Project Public: 

Test Project https://github.com/andy952737/test_2fa 

Ruby3.3.0, Rails7.x以上