1

我正在使用Rails 5和Devise进行Ajax身份验证。表格用户列已被阻止,如果用户被阻止,他将被注销。我已经设置标题为阿贾克斯全球:InvalidAuthenticityToken,Ajax,Rails 5 with Device

$(document).ajaxSend(function(e, xhr, options) { 
    var token = $("meta[name='csrf-token']").attr("content"); 
    xhr.setRequestHeader("X-CSRF-Token", token); 
}); 

这是替换SessionsController创建方法:

def create 
    if warden.authenticate(:scope => resource_name) 
     if current_user.blocked 
      sign_out(@user) 
      return render json: {blocked: true} 
     else 
      return render json:{success: true} 
     end 
    else 
     return render json: {error: true} 
    end 
end 

如果用户被封锁,他试图验证来自服务器的响应是{blocked: true}。而无需刷新页面,如果他再次尝试的响应是一个错误:

的ActionController :: InvalidAuthenticityToken在用户:: SessionsController#创建 的ActionController :: InvalidAuthenticityToken 提取的源(左右线#195):

我在标题中看到每次用户尝试登录时都会发送令牌。 我知道可能是问题是因为第一次登录后令牌被更改,但因为请求是使用Ajax它可以获得新的令牌,但我不知道如何解决该问题。

回答

1

您可以使用ajaxComplete事件完成ajax并在完成登录请求后设置meta [name ='csrf-token']内容。

相关问题