2016-01-20 30 views
1

我想在用戶代理和/或用戶IP更改時重置會話。項目使用Rails與Devise進行身份驗證,CanCanCan進行授權。基於用戶代理和/或ip更改重置會話。 Rails與設計

我的做法是:

class ApplicationController < ActionController::Base 

    before_action :authorize_ip 

    def authorize_ip 
    if warden.authenticated? 
     warden.session['ip'] ||= request.ip 
     warden.session['user_agent'] ||= request.user_agent 
     warden.logout if warden.session['ip'] != 'request.ip' && 
     warden.session['user_agent'] != request.user_agent 
    end 
    end 
end 

從我的理解,它應該設置warden.session['ip']和USER_AGENT一次,然後進行以下請求時request['ip']或USER_AGENT變化,會議應丟棄,用戶應該註銷。但是,當使用不同的瀏覽器進行測試時,warden.session['user_agent']會根據我使用的瀏覽器而改變。我想我是誤解了一些東西。另外,如果有更好的方法解決這個問題,請分享。

謝謝!

+0

基本上你正在做的事情是行不通的,因爲它取決於在過濾器鏈的順序上。我會考慮創建一個[自定義身份驗證策略](http://stackoverflow.com/questions/4223083/custom-authentication-strategy-for-devise)。然而,我個人在使用移動連接時使用基於IP的身份驗證解決方案存在很多問題 - 特別是在3個世界各國。檢查用戶代理是一種很少有優點的神祕練習,因爲它很容易被欺騙。 – max

+0

感謝您的提示。我試過編寫一個守望者戰略,但是我遇到了兩個問題:1)守望者似乎只在登錄時進行身份驗證,並且這裏的目標是在用戶登錄後驗證(授權?)每個請求。2)對於某些甚至在''''''''''''''''''''''有效?''''Warden仍然執行驗證方法,因此破壞了登錄頁面上的所有內容。第一個問題使第二種不相關。 – ntfx

回答

2

我加入這初始化/ devise.rb

Warden::Manager.after_authentication do |_user, auth, _opts| 
    auth.raw_session['warden.user.ip'] = auth.request.ip 
    auth.raw_session['warden.user.user_agent'] = auth.request.user_agent 
    end 

解決這個問題,這給應用控制器:

class ApplicationController < ActionController::Base 

    before_action :authorize_ip_user_agent 

    protected 

    def authorize_ip_user_agent 
    return true unless session['warden.user.ip'] 
    warden.logout if session['warden.user.ip'] != request.ip && 
     session['warden.user.user_agent'] != request.user_agent 
    end 
end