0

Ran into a headache. I'm trying to set an ajaxPreFilter to constantly refresh an API Token prior to each request.

I've got the whole structure built and everything working (including refreshing the token) apart from the actual setting of the Request header with the API token.

var currentRequests = {};

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    
    //don't do the prefilter code for the refresh_token function and login function
    if(options.url == 'API_URL/api/auth/refresh_token' || options.url == 'API_URL/api/auth/login') {
        return;
    }
    successCallback = function(token)
    {
         jqXHR.setRequestHeader("X-Api-Token", token);
    };
    errorCallback = function() {
        console.error("Could not refresh token, aborting Ajax call to " + options.url);
        currentRequests[options.url].abort();
    };

    check_token_expiry(successCallback, errorCallback);
});

function check_token_expiry(successCallback, errorCallback)
{
    current_api_token               = localStorage.getItem("api_token");
    current_refresh_token           = localStorage.getItem("refresh_token");
    current_api_token_expiry        = localStorage.getItem("api_token_expiry");
    current_refresh_token_expiry    = localStorage.getItem("refresh_token_expiry");

    time_now                        = Math.floor(Date.now() / 1000);

    if(current_refresh_token_expiry > time_now)
    {
        $.ajax({
            type: 'POST',
            url: "API_URL/api/auth/refresh_token",
            data: "refresh_token=" + current_refresh_token
        }).done(function(data) {
            if(data.status == 'success') {
                localStorage.setItem("api_token", data.token);
                localStorage.setItem("refresh_token", data.refresh_token);
                localStorage.setItem("api_token_expiry", data.token_expiry);
                localStorage.setItem("refresh_token_expiry", data.refresh_token_expiry);
                successCallback(data.token);
            }
        }).fail(function(data) {
            errorCallback(data);
        });
    }
    else
    {
       window.location.href = "login.html";
    }
}

I think my problem lies within the successCallback function but not sure how to apply the RequestHeader to each of the ajax calls. I've tried just using localStorage.getItem("api_token") within the call directly but it's still grabbing the previous value which was the reason I started down this route in the first place rather than just using beforeSend();

Any help would be much appreciated.

user1530205
  • 302
  • 6
  • 19

1 Answers1

-1

if it's retrieving the previous value localstorage is that because it hasn't set the value before the refresh call is made?

would something like this work

$("body").bind("ajaxSend", function(elm, xhr, s){
          if (s.type == "POST") {
              xhr.setRequestHeader('....', '....');
          }
});

out of interest why can't you use beforeSend ?

Patrick Hume
  • 2,064
  • 1
  • 3
  • 11
  • I assumed beforeSend would work but..... the value in localStorage does not update quickly enough thus it uses the previous value instead. again I'm assuming its due to the asynchronous call when setting the new token. It's the reason I'm using the callback in the ajaxPreFilter instead so it's physically passing the token through rather than relying on localstorage updating quickly enough but no idea how to set the Request Header from within there. I'll give your answer a go and let you know. Thanks – user1530205 Sep 01 '22 at 07:34
  • not sure why someone downvoted my above answer, it's a widely used method but ok, in any case, if that fails take a look at this see if this helps https://stackoverflow.com/questions/20356374/add-custom-http-header-to-all-jquery-ajax-requests – Patrick Hume Sep 01 '22 at 19:19