gpt4 book ai didi

reactjs - React-admin JWT身份验证刷新 token 问题

转载 作者:行者123 更新时间:2023-12-03 14:22:44 26 4
gpt4 key购买 nike

我想为react-admin实现我自己的authProvider,但我陷入困境。
我使用 Django-Rest-Framework 后端和 JWT token 身份验证系统。
如果 JWT token 在每次请求之前几乎过期,我想刷新它。根据文档,authProvidercheckAuth 函数在每次 API 调用之前都会被调用,这是事实。我的问题是,对于我的代码,它不会等待 promise 完成,而是使用旧的访问 token ,这会导致 401,并且我会被重定向到登录页面。我缺少什么指导吗?

import jwt from 'jsonwebtoken';


export default {
login: async ({ username, password }) => {
const request = new Request('http://localhost:8000/api/token/', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
});

const response = await fetch(request);
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
const { refresh, access } = await response.json();
localStorage.setItem("refreshToken", refresh);
localStorage.setItem("accessToken", access);
},

logout: params => {
console.log("logout");
localStorage.setItem('accessToken', "");
localStorage.setItem('refreshToken', "");

return Promise.resolve();
},

checkAuth: (params) => {
const accessToken = localStorage.getItem('accessToken');
const refreshToken = localStorage.getItem('refreshToken');

if (accessToken && refreshToken) {
console.log(accessToken);
const { exp } = jwt.decode(accessToken);
if (exp > (new Date().getTime() / 1000) - 10) {
return Promise.resolve();
} else {
const request = new Request('http://localhost:8000/api/token/refresh/', {
method: 'POST',
body: JSON.stringify({ "refresh": refreshToken }),
headers: new Headers({ 'Content-Type': 'application/json' }),
});

const response = fetch(request)
.then(response => {
if (response.status !== 200) {
throw new Error(response.statusText);
}
return response.json();
})
.then(({ token }) => {
localStorage.setItem('accessToken', token);
return Promise.resolve();
});

return response;
}
}
return Promise.reject();
},

checkError: error => {
if (error.status === 401 || error.status === 403) {
return Promise.reject();
}
return Promise.resolve();
},
getPermissions: params => Promise.resolve(),
}

最佳答案

你能尝试这样的事情吗

checkAuth: async (params) =>

还有

  const request = new Request(...);

let data;
const response = await fetch(request);
if (response.ok) data = await response.json()
else throw new Error(response.statusText);

if (data && data.token) {
localStorage.setItem('accessToken', data.token);
console.log(data.token);
return Promise.resolve();
} else return Promise.reject();

关于reactjs - React-admin JWT身份验证刷新 token 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233033/

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