2012-10-26 99 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