2012-10-26 88 views
2

我有以下這些行動這一問題制定:設計登錄,但未經授權的

  • 我註冊一個新用戶(正常工作)
  • 我確認用戶的郵件(正常工作)。那時我正常登錄,一切正常。
  • 現在,如果我註銷並嘗試重新登錄,則會收到未經授權的錯誤(401)。

望着這裏的服務器日誌會發生什麼:

Started POST "https://stackoverflow.com/users/sign_in" for 127.0.0.1 at 2012-10-26 10:26:23 +0200 
Processing by Users::SessionController#create as JSON 
    Parameters: {"email"=>"[email protected]", "password"=>"[FILTERED]",  "remember_me"=>"0"} 
WARNING: Can't verify CSRF token authenticity 
    User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`email` =  '[email protected]' LIMIT 1 
    (1.0ms) BEGIN 
    (0.0ms) COMMIT 
    (1.0ms) BEGIN 
    (0.0ms) UPDATE `users` SET `current_sign_in_at` = '2012-10-26 08:26:23', `sign_in_count` = 2, `updated_at` = '2012-10-26 08:26:23' WHERE `users`.`id` = 1 
    (25.0ms) COMMIT 
    Rendered devise/sessions/create.json.rabl (1.0ms) 
Completed 200 OK in 135ms (Views: 22.0ms | ActiveRecord: 27.0ms) 


Started GET "/accounts/new" for 127.0.0.1 at 2012-10-26 10:26:23 +0200 
Processing by AccountsController#new as HTML 
Completed 401 Unauthorized in 0ms 

正如你所看到的,我登錄,我甚至想獲得視圖渲染(devise/sessions/create.json.rabl)和右後我重定向到/帳戶/新'我不被授權了。然後,我可以嘗試訪問我想要的任何網址並繼續收到未經授權的郵件。

我想這對一個新的數據庫(DB:重置),我試圖日誌之前在清理餅乾

任何想法,這種行爲可能來自?

我在Rails 3.2.8中使用Devise 2.1.2。

UPDATE

按照要求:AccountsController代碼:

class AccountsController < ApplicationController 
    before_filter :authenticate_user! 

    def :index 
    @accounts = current_organization.accounts 
    end 

    def new 
    @account = Account.new(:organization => current_organization) 
    end 

    def create 
    @account = Account.new(params[:account]) 
    @account.organization = current_organization 
    if @account.save 
     redirect_to :index 
    else 
     #TODO 
    end 
    end 
end 
+0

代碼'AccountsController#new'將是非常有益 – shime

+0

只是把它添加到主哨,謝謝。 – muichkine

+0

您沒有添加'new'行動。 – shime

回答

2

你應該這樣做:

  1. 請確保您有<%= csrf_meta_tag %>在佈局

  2. 添加beforeSend所有Ajax請求設置頭象下面這樣:


$.ajax({ url: 'YOUR URL HERE', 
    type: 'POST', 
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, 
    data: 'someData=' + someData, 
    success: function(response) { 
    $('#someDiv').html(response); 
    } 
}); 

來源:WARNING: Can't verify CSRF token authenticity rails


Althoug這種情況正在發生,因爲你啓用了模型:token_authentication

你可能不想要這個。


否則,如果你想跳過認證只是爲AJAX請求你可以這樣做:

skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' } 

關於你真正的錯誤,是不是因爲你簽了:authenticate_user!用戶並在代碼中使用current_organization

所以如果是通過驗證它不會necessarely有current_organization價值!

希望它有幫助!

+0

你的回答是要命。現在一切都再次運作!謝謝。 – muichkine

+0

你錯了,必須<(%)= csrf_meta_tags%> – nilid