feat: enhance security by implementing HttpOnly refresh tokens and in-memory access token management
- Added isomorphic-dompurify for improved XSS protection - Refactored token storage to use in-memory management for access tokens - Implemented server-side route handlers for OAuth token management - Introduced security headers in next.config.js - Removed client-side exposure of client_secret and sensitive tokens - Updated API interceptors to handle token refresh logic - Cleaned up cookie management for refresh tokens
This commit is contained in:
+54
-24
@@ -1,6 +1,7 @@
|
||||
import axios from "axios";
|
||||
import Cookies from "js-cookie";
|
||||
import { toast } from "react-toastify";
|
||||
import { getAccessToken, setAccessToken, clearAccessToken } from "@/lib/tokenStore";
|
||||
|
||||
function extractErrorMessage(error) {
|
||||
const errors = error?.response?.data?.errors;
|
||||
@@ -17,48 +18,77 @@ const BASE_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
"X-CSRF-Token": "",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
// اضافه کردن interceptor برای افزودن token به ریکوستهایی که نیاز به احراز هویت دارند
|
||||
let refreshPromise = null;
|
||||
|
||||
async function refreshAccessToken() {
|
||||
if (!refreshPromise) {
|
||||
refreshPromise = fetch("/api/auth/refresh", { method: "POST" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((data) => {
|
||||
const token = data?.access_token ?? null;
|
||||
setAccessToken(token);
|
||||
return token;
|
||||
})
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
refreshPromise = null;
|
||||
});
|
||||
}
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
function handleSessionExpired() {
|
||||
clearAccessToken();
|
||||
const hostname = window.location.hostname;
|
||||
const domain = hostname.includes("localhost")
|
||||
? undefined
|
||||
: `.${hostname.split(".").slice(-2).join(".")}`;
|
||||
const opts = { path: "/", ...(domain && { domain }) };
|
||||
["uuid", "userInfo"].forEach((key) => Cookies.remove(key, opts));
|
||||
window.location.href = "/login";
|
||||
}
|
||||
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
// فقط اگر requireAuth در config تنظیم شده باشد، token اضافه میشود
|
||||
if (config.requireAuth) {
|
||||
const token = Cookies.get("access_token");
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
api.interceptors.response.use(
|
||||
(response) => {
|
||||
return response.data;
|
||||
},
|
||||
(error) => {
|
||||
if (typeof window !== "undefined") {
|
||||
if (error?.response?.status === 401) {
|
||||
const hostname = window.location.hostname;
|
||||
const domain = hostname.includes("localhost")
|
||||
? undefined
|
||||
: `.${hostname.split(".").slice(-2).join(".")}`;
|
||||
const opts = { path: "/", ...(domain && { domain }) };
|
||||
["access_token", "refresh_token", "uuid", "userInfo"].forEach((key) => {
|
||||
Cookies.remove(key, opts);
|
||||
});
|
||||
window.location.href = "/login";
|
||||
} else if (!error?.config?.skipErrorToast) {
|
||||
toast.error(extractErrorMessage(error));
|
||||
(response) => response.data,
|
||||
async (error) => {
|
||||
const original = error?.config;
|
||||
|
||||
if (
|
||||
error?.response?.status === 401 &&
|
||||
original?.requireAuth &&
|
||||
!original._retried &&
|
||||
typeof window !== "undefined"
|
||||
) {
|
||||
original._retried = true;
|
||||
const token = await refreshAccessToken();
|
||||
if (token) {
|
||||
original.headers = { ...original.headers, Authorization: `Bearer ${token}` };
|
||||
return api(original);
|
||||
}
|
||||
handleSessionExpired();
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined" && !error?.config?.skipErrorToast) {
|
||||
toast.error(extractErrorMessage(error));
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user