L
L
lexstile2021-12-15 18:24:05
JavaScript
lexstile, 2021-12-15 18:24:05

How to properly handle getting an access token in interceptors on axios?

There is the following situation, to which I can not find an approach:
1. We call some method (GET, POST ...)
2. In interceptors, we check the token for an expired period
3. If the token is expired, we suspend the execution of the current request
4. We receive a token
5 We continue the execution of the query that we remembered before

Perhaps there are ready-made templates for solving such problems?
Or any suggestion? Tip?
I will be grateful for any information.

export const http = axios.create();
const currentExecutingRequests = {};

http.interceptors.request.use(
  (req) => {
    let originalRequest = req;

    if (currentExecutingRequests[req.url]) {
      const source = currentExecutingRequests[req.url];
      delete currentExecutingRequests[req.url];
      source.cancel('Отмена запроса');
    }

    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    originalRequest.cancelToken = source.token;
    currentExecutingRequests[req.url] = source;

    return originalRequest;
  },
  (err) => {
    return Promise.reject(err);
  }
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bart0725, 2021-12-16
@lexstile

My solution, which I use when authorizing to QC

import _ from 'lodash';
const mainFetch = axios.create();

export const issueToken = () => {
    return new Promise((resolve, reject) => {
        return keycloak.updateToken(30000).success((refreshed) => {
            if (refreshed) {
                resolve(keycloak.token);
                sessionStorage.setItem("kctoken", `${keycloak.token}`);
            } else {
                console.log('not refreshed ' + new Date());
            }
        }).error(() => {
            reject();
            keycloakLogout();
        });
    });
}

mainFetch.interceptors.request.use((config) => {
    let originalRequest = config;
    if (keycloak.isTokenExpired(30000)) {
        return issueToken().then((token) => {
            _.set(originalRequest, 'headers.Authorization', `Bearer ${token}`);
            return Promise.resolve(originalRequest);
        });
    } else {
        _.set(config, 'headers.Authorization', `Bearer ${sessionStorage.getItem("kctoken")}`);
    }
    return config;
}, (err) => {
    return Promise.reject(err);
});

It works like this, when requesting, we turn to the CC with the special isTokenExpired method in my case, 30 seconds before it expires, if the time expires, we request a new one and return the config with a new token, if not, we take the token from the session

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question