Home InvalidAuthenticityToken, Ajax, Rails 5 with Device
Reply: 1

InvalidAuthenticityToken, Ajax, Rails 5 with Device

gdfgdfg Published in 2017-12-02 17:16:39Z

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
            return render json: {blocked: true}
            return render json:{success: true}
        return render json: {error: true}

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.

Prince Bansal
Prince Bansal Reply to 2017-12-02 18:41:28Z

You can use ajaxComplete event upon ajax completion and set meta[name='csrf-token'] content upon after login request complete.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.341033 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO