InvalidAuthenticityToken, Ajax, Rails 5 with Device

I am using Ajax authentication with Rails 5 and Devise. The table users has column blocked and if the user is blocked he will be logged out. I have set header for Ajax globally:

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

This is the replaced create method in 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

If the user is blocked and he tries to authenticate the response from the server is {blocked: true} . Without refreshing the page, if he tries again the response is an error :

ActionController::InvalidAuthenticityToken in Users::SessionsController#create ActionController::InvalidAuthenticityToken Extracted source (around line #195):

I see in the headers that the token is send every time when user tries to login. I know that may be the problem is because after first time login the token is changed, but because the request is with Ajax it can get the new token, but I don't know how to fix that.


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

链接地址: http://www.djcxy.com/p/81146.html

上一篇: 有没有办法以编程方式生成CouchDB cookie?

下一篇: InvalidAuthenticityToken,Ajax,带设备的Rails 5