کانال نوحه و مداحی ناب

best way of handling access token in react .js?

best way of handling access token in react .js?

Managing access tokens securely in React is crucial to prevent security risks like token theft and unauthorized access. Here’s the best approach depending on your authentication strategy:

 

1️⃣ Store Tokens Securely

Instead of localStorage, consider safer alternatives:

HttpOnly Cookies (Recommended)

  • Tokens are stored on the server and not accessible to JavaScript, preventing XSS attacks.

  • Use SameSite=Strict and Secure flags for better protection.

Session Storage (Better Than LocalStorage)

  • Clears automatically when the session ends.

  • Still accessible by JavaScript, so not ideal for highly sensitive tokens.

Redux or React State (For Short-Lived Tokens)

  • Stores tokens in memory, preventing exposure to persistent storage attacks.

  • Good for apps using short-lived tokens and refresh mechanisms.

 

2️⃣ Implement Token Expiry & Refresh Mechanism

To avoid stale tokens and frequent logouts, implement token refreshing using refresh tokens.

🔹 Example: Automatic Token Refresh with Axios Interceptors

javascript

import axios from 'axios';

// Create an Axios instance
const api = axios.create({
  baseURL: 'https://your-api.com',
  withCredentials: true // Ensures cookies are sent
});

// Request interceptor to attach token
api.interceptors.request.use(config => {
  const accessToken = sessionStorage.getItem("access_token");
  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`;
  }
  return config;
});

// Response interceptor to handle token expiry
api.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 401) {
      // Try refreshing the token
      const refreshToken = sessionStorage.getItem("refresh_token");
      if (refreshToken) {
        const { data } = await axios.post("https://your-api.com/refresh", { refresh_token: refreshToken });
        sessionStorage.setItem("access_token", data.access_token);
        error.config.headers.Authorization = `Bearer ${data.access_token}`;
        return api(error.config); // Retry original request
      }
    }
    return Promise.reject(error);
  }
);

export default api;
 

3️⃣ Protect Routes with Authentication Checks

Ensure users are redirected if their token is missing or expired.

🔹 Example: Private Route Protection

javascript

import { Navigate, Outlet } from "react-router-dom";

const PrivateRoute = () => {
  const accessToken = sessionStorage.getItem("access_token");

  return accessToken ? <Outlet /> : <Navigate to="/login" />;
};

export default PrivateRoute;
 

✅ Summary of Best Practices

🔒 Store tokens securely (HttpOnly Cookies or Session Storage) 🔄 Use a refresh token system to prevent forced logouts 🚀 Protect routes with authentication checks 📡 Use Axios interceptors for automatic token handling

 

کانال نوحه و مداحی ناب

نظرات (۰)
هیچ نظری هنوز ثبت نشده است

ارسال نظر

ارسال نظر آزاد است، اما اگر قبلا در بیان ثبت نام کرده اید می توانید ابتدا وارد شوید.
شما میتوانید از این تگهای html استفاده کنید:
<b> یا <strong>، <em> یا <i>، <u>، <strike> یا <s>، <sup>، <sub>، <blockquote>، <code>، <pre>، <hr>، <br>، <p>، <a href="" title="">، <span style="">، <div align="">
تجدید کد امنیتی