我使用令牌作为授权,当令牌过期时,我想使用刷新令牌创建一个新令牌。我可以使用axios库来执行此操作,但是找不到umi请求来执行此操作。有人将下面给出的代码示例转换为umi请求拦截器示例吗?
此axios拦截器响应我的刷新令牌操作。
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请求刷新令牌,但是我做不到,因为在axios库中,我无法编写umi请求,也无法建立其逻辑。那么,有人可以为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]
};
答案 0 :(得分:0)
这是我在 umi-request/ant-design-pro 中处理刷新令牌的解决方案,不需要 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