gpt4 book ai didi

javascript - 如何在 react js redux 中添加刷新 token 功能

转载 作者:行者123 更新时间:2023-12-03 07:13:10 28 4
gpt4 key购买 nike

我正在开发一个具有刷新 token 功能的应用程序。为此,我在网上学习了Axios interceptor后尝试实现这个功能。但是,它仍然没有解决。这就是我添加的方式。

不知道是对是错。我刚刚尝试实现刷新 token 。我以前不知道刷新 token 。

任何帮助都会很棒。

index.js

axios.interceptors.request.use(
(config) => {
console.log("step-1", config);
const token = localStorageService.getAccessToken();
if (token) {
config.headers["Authorization"] = "Bearer" + token;
}
return config;
},
(error) => {
Promise.reject(error);
}
);

axios.interceptors.response.use(
(response) => {
console.log("step-2", response);
return response;
},
function (error) {
const originalRequest = error.config;

// if (error.response && error.response.status === 401 && !originalRequest._retry) {
// history.push("/");
// return Promise.reject(error);
// }

if (
error.response &&
error.response.status === 401 &&
!originalRequest._retry
) {
originalRequest._retry = true;

const token = UserServices.getOAuth2().createToken(
"refresh_token",
localStorageService.getRefreshToken(),
{ grant_type: "refresh_token" }
);

return token
.refresh()
.then((res) => {
console.log("step3", res);
if (res.status === 201) {
// 1) put token to LocalStorage
localStorageService.setToken(res.data);
// 2) Change Authorization header
axios.defaults.headers.common["Authorization"] =
"Bearer " + localStorageService.getAccessToken();
// 3) return originalRequest object with Axios.
return axios(originalRequest);
}
})
.catch((error) => {
// Dispatch Logout Function here
store.dispatch({
type: LOGIN_ERROR,
});
localStorageService.clearToken();
});
}
}
);

userServices.js

const localStorageService = LocalStorageService.getService();
class UserServices {
getOAuth2 = () => {
var ClientOAuth2 = require("client-oauth2");
const OAuth2 = new ClientOAuth2({
clientId: "development",
clientSecret: "development",
accessTokenUri: "https://api.xxxx.in/oauth/token",
authorizationUri: "https://api.xxxx.in/oauth/authorize",
redirectUri: "https://api.xxxx.in/oauth/callback",
scopes: ["read", "write", "trust"],
});
return OAuth2;
};

logout() {
localStorageService.clearToken();
}
}

最佳答案

我相信你需要在你的错误处理程序中调用 resolve 并且它应该修复它:

return token
.refresh()
.then((res) => {
console.log("step3", res);
if (res.status === 201) {
// 1) put token to LocalStorage
localStorageService.setToken(res.data);
// 2) Change Authorization header
axios.defaults.headers.common["Authorization"] =
"Bearer " + localStorageService.getAccessToken();
// 3) return originalRequest object with Axios.
res(axios(originalRequest)); // <- call resolve here
}
})
.catch((error) => {
// Dispatch Logout Function here
store.dispatch({
type: LOGIN_ERROR,
});
localStorageService.clearToken();
});

关于javascript - 如何在 react js redux 中添加刷新 token 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63027267/

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