Search code examples
javascriptxmlhttprequestaxiosbearer-token

Axios headers authorization bearer is missing on callback


I am working currently with Javascript and Axios, on a client side application. I run an axios request (refreshToken();) with an other axios request callback (userAuth();), in the response of the first axios request I receive a new Token. I try to set this new Token in the headers authorization bearer of my callback. This doesn't work : On the callback (userAuth();) the new token is not set, and there is no more Authorization Bearer set in the headers.

When userAuth(); is not a callback, the Authorization Bearer is set correctly. When userAuth(); is a callback, the Authorization Bearer is not set.

let now = new Date();
let time = now.getTime();
time += 3600 * 1000;
now.setTime(time);

const setTokenOnCookie = (token) => {
    document.cookie = 'token=' + token + '; expires=' + now.toUTCString();
}

const setRefreshOnCookie = (refresh_token) => {
    document.cookie = 'refresh_token=' + refresh_token;
}

const TOKEN_USER = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");
const REFRESH_TOKEN = document.cookie.replace(/(?:(?:^|.*;\s*)refresh_token\s*\=\s*([^;]*).*$)|^.*$/, "$1");

const refreshToken = (userAuthCallback, userUnauthCallback) => {
    axios.post(`${API_URL}/my/url/to/refresh/token`,
        'refresh_token='+REFRESH_TOKEN,
        {headers:{'Content-Type': 'application/x-www-form-urlencoded'}}
    ).then(res => {
        Promise.all([setTokenOnCookie(res.data.token), setRefreshOnCookie(res.data.refresh_token)])
    .then(()=>{
         userAuthCallback(res.data.token);
     }).catch(err => {
         userUnauthCallback();
     })
}

const userAuth = (token) => {
    if(!token){
        token = TOKEN_USER
    }
    axios.get(`${API_URL}/my/url/to/get/my/user`,
        {headers:{'Authorization': `Bearer ${token}`}}
    ).then(res => {
        pushToApplicationPath();
    }).catch(err => {
        catchMyError();
    })
}

const userUnauth = () => {
    document.cookie = 'token=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    document.cookie = 'refresh_token=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    document.cookie = 'username=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    pushToLoginPath();
}

refreshToken(userAuth, userUnauth);

Do you know where the problem is ?


Solution

  • I have found the open issue on GitHub.

    GitHub issue 891