对于上下文,登录时我将刷新令牌和访问令牌发送到仅http cookie中,这很好,我设置了一个间隔,通过每8秒点击“刷新令牌”端点来刷新客户端的访问令牌,这在刷新访问令牌方面工作得很好,但是当我重新加载页面时,访问令牌不再刷新:(
注意:出于测试目的,我的刷新令牌到期时间设置为“1m”,访问令牌到期时间设置为“10s”。我设置了一个间隔,每 8 秒刷新一次访问令牌
这是我的 useAuthentication 挂钩:
import { useState, useEffect } from "react";
import axios from "axios";
import { useLocation } from "react-router-dom";
import { useRefreshAccessToken } from "./useRefreshAccessToken"; // Import the custom hook
axios.defaults.withCredentials = true;
export function useAuthentication() {
const [isAuthenticated, setIsAuthenticated] = useState(
!!localStorage.getItem("user")
);
const [user, setUser] = useState(null);
const [userId, setUserId] = useState(null);
const location = useLocation();
const getUser = async () => {
const response = await axios.get("http://localhost:3001/getUser", {
withCredentials: true,
});
return response;
};
useEffect(() => {
getUser()
.then((response) => {
setUser(response.data?.user);
setUserId(response.data?.user._id);
})
.catch(() => {
setIsAuthenticated(false);
localStorage.removeItem("user");
});
}, [location.pathname]);
useRefreshAccessToken(userId, setIsAuthenticated);
const handleLogout = () => {
localStorage.removeItem("user");
setIsAuthenticated(false);
setUser(null);
window.location.reload();
};
return { isAuthenticated, user, handleLogout };
}
这是我的 useRefreshAccessToken 挂钩:
import { useEffect } from "react";
import axios from "axios";
axios.defaults.withCredentials = true;
export function useRefreshAccessToken(userId, setIsAuthenticated) {
const _AT_APPROX_EXP = 8000;
useEffect(() => {
const refreshAccessToken = async () => {
try {
await axios.post("http://localhost:3001/refresh", {
withCredentials: true,
data: { userId },
});
} catch (error) {
console.log(error);
setIsAuthenticated(false);
localStorage.removeItem("user");
}
};
const intervalId = setInterval(() => {
refreshAccessToken();
}, _AT_APPROX_EXP);
return () => clearInterval(intervalId);
}, [userId]);
}