gpt4 book ai didi

javascript - umi 请求拦截器响应的 Refresh Token

转载 作者:行者123 更新时间:2023-12-04 17:26:05 24 4
gpt4 key购买 nike

我使用 token 作为授权,当 token 过期时,我想使用刷新 token 创建一个新 token 。我可以用 axios 库做到这一点,但我找不到如何用 umi 请求做到这一点。有人将下面给出的代码示例翻译成一个 umi 请求拦截器示例吗?
这个 axios 拦截器响应我的刷新 token 操作。

  let isRefreshing: boolean = false;
let failedQueue: any = [];

const processQueue = (error: any, token: any = null) => {
failedQueue.forEach((prom: any) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token);
}
});

failedQueue = [];
};

axios.interceptors.response.use(
async response => {
return response;
},
async error => {
debugger;
const originalRequest = error.config;
if (error.response) {
const status = error.response.status;
const refreshToken = getStoredUserAuth().refreshToken;
if (status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise(function(resolve, reject) {
failedQueue.push({ resolve, reject });
})
.then(token => {
originalRequest.headers["Authorization"] = "Bearer " + token;
return axios(originalRequest);
})
.catch(err => {
return Promise.reject(err);
});
}

originalRequest._retry = true;
isRefreshing = true;

return new Promise(function(resolve, reject) {
refreshAccessToken(refreshToken)
.then(response => {
if (response.status === 200) {
if (response.data.token) {
setAuthStatus(response.data);
axios.defaults.headers.common["Authorization"] =
"Bearer " + response.data.token;
originalRequest.headers["Authorization"] =
"Bearer " + response.data.token;
}
processQueue(null, response.data.token);
resolve(axios(originalRequest));
} else {
throw new Error();
}
})
.catch(err => {
//console.log(err);
failedQueue = [];
setUnauthStatus();
source.cancel("Session time out");
processQueue(err, null);
reject(err);
})
.then(() => {
isRefreshing = false;
});
});
}
} else {
debugger;
errorHandler(error);
}
return Promise.reject(error);
}
);
我用的是ant design pro V5版本,所以尝试用umi request来刷新token,但是不行,在axios库中,不能写umi request,也不能建立它的逻辑。那么任何人都可以为 umi 请求编写上面相同的示例(axios.interceptors.response)吗?
const requestInterceptors = (url: string, options: RequestOptionsInit) => {
if (tokenService.check()) {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${tokenService.parse()?.token}`,
};
return {
url,
options: { ...options, headers },
};
}
return {
url,
options: { ...options },
};
};

const responseInterceptors = (response: Response, options: RequestOptionsInit) => {

// I could'nt this part for refresh token like axios interceptors. I need help for that

return response;
}

export const request: RequestConfig = {
errorHandler,
requestInterceptors: [requestInterceptors],
responseInterceptors: [responseInterceptors]
};
umi request github link for documentation

最佳答案

这是我在 umi-request/ant-design-pro 中处理刷新 token 的解决方案,不需要 queue s,就像一个魅力

// Neccesary imports
import type { RequestConfig } from 'umi';
import { request as requestUmi } from 'umi';
import type {
RequestInterceptor,
RequestOptionsInit,
ResponseError,
} from 'umi-request';
import Reqs from 'umi-request';
import merge from 'lodash/merge';
import cloneDeep from 'lodash/cloneDeep';

// My personal type definitions
namespace API {
export interface LoginResult {
access: string;
refresh: string;
}
}

// Part 1: "Simple" Error Handler =))
const errorHandler = (error: ResponseError) => {
console.log('HTTP ERROR', error);
throw error;
};

// Part 2: Request Interceptors, (use this instead of "headers" directly in request config)
const requestInterceptor: RequestInterceptor = (url, options) => {
return {
url,
options: merge(cloneDeep(options), {
headers: { Authorization: `Bearer ${jwt.getAccess()}` },
}),
};
};

// Part 3: Response Interceptos
const { cancel } = Reqs.CancelToken.source();
let refreshTokenRequest: Promise<API.LoginResult> | null = null;
const responseInterceptor = async (
response: Response,
options: RequestOptionsInit
) => {
const accessTokenExpired = response.status === 401;
if (accessTokenExpired) {
try {
if (!refreshTokenRequest) {
refreshTokenRequest = refreshAccessToken(jwt.getRefresh());
}
// multiple requests but "await"ing for only 1 refreshTokenRequest, because of closure
const res = await refreshTokenRequest;
if (!res) throw new Error();
if (res.access) jwt.saveAccess(res.access);
if (res.refresh) jwt.saveRefresh(res.refresh); // for ROTATE REFRESH TOKENS
return requestUmi(
response.url,
merge(cloneDeep(options), {
headers: { Authorization: `Bearer ${res.access}` },
})
);
} catch (err) {
jwt.removeAccess();
jwt.removeRefresh();
cancel('Session time out.');
throw err;
} finally {
refreshTokenRequest = null;
}
}

return response;
};

export const request: RequestConfig = {
errorHandler,
// This would fuck the refresh token logic, use requestInterceptors instead,
// because jwt.getAccess() will not being called everytime, but only the first time => lead to stale access token
// headers: { Authorization: `Bearer ${jwt.getAccess()}` },

// Handle refresh token (old): https://github.com/ant-design/ant-design-pro/issues/7159#issuecomment-680789397
// Handle refresh token (new): https://gist.github.com/paulnguyen-mn/8a5996df9b082c69f41bc9c5a8653533
requestInterceptors: [requestInterceptor],
responseInterceptors: [responseInterceptor],
};
还贴了 here

关于javascript - umi 请求拦截器响应的 Refresh Token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63340790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com