所以我有一个带Jwt令牌的ASP net core 3.0后端,我在Api中实现了刷新令牌,所以我遇到了Axios和刷新令牌方法的问题,所以我有很多来自后端的验证代码,我想使用Axios拦截器实现刷新令牌,但是那根本没有用,所以我希望有人能在其中给出一些提示,我设法使其正常工作,但是在我第一次遇到时它没有重复原始请求刷新页面以使其正常工作。这是我的Axios代码中的提示。
axios.interceptors.request.use(
config => {
const token = getJwt();
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
// config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error);
}
);
const originalRequest = error.config;
console.log("this is orginal request ", originalRequest);
const expectedError =
error.response &&
error.response.status >= 400 &&
error.response.status < 500; if (!expectedError) {
logger.log(error.response);
toast.error("An unexpected error occurrred.");
return Promise.reject(error);
} if (
error.response.status === 401 &&
originalRequest.url === refreshTokenUrl
) {
console.log("not refreeeeeehhhhh here error 401 with referech url ");
CleanJwt();
window.location = "/login";
return Promise.reject(error);
}
if (error.response.status == 401 && !originalRequest._retry) {
let tokenRefresh = {
token: getJwt(),
refreshToken: getRefreshToken()
};
await axios.post(refreshTokenUrl, tokenRefresh).then(response => {
console.log(response);
if (response.status === 200) {
originalRequest._retry = true;
localStorage.setItem("token", response.data.token);
localStorage.setItem("refreshToken", response.data.refreshToken);
originalRequest.headers.Authorization = "Bearer " + response.data.token;
return axios(originalRequest);
}
});
return Promise.resolve();
}
if (
error.response.status == 400 &&
error.response.data == "UserName Or Password Not Correct"
) {
alert(error.response.data);
console.log("alert false login ");
logger.log(error.response);
} else {
if (error.response.status == 400) {
let message = "Validation Exception , fill the Form with correct inputs ";
logger.log(error.response);
toast.error(message);
}
}
if (error.response.status == 404) {
let message = " Not Found ";
logger.log(error.response);
toast.error(message);
return Promise.reject(error);
}
if (error.response.status == 406) {
let message = " User Identity Error ";
logger.log(error.response);
toast.error(message);
}
return Promise.reject(error);
});