在react和laravel中实现自动注销功能

问题描述 投票:0回答:1

我正在创建一个项目,因此在我的项目中它会生成令牌,我为此使用 laravel sainttum,所以我想当令牌过期时,我想自动注销并再次导航到我的登录页面,我将如何做到这一点我会将自动注销功能放在 login.jsx 文件、RequireAuth.jsx 还是我的 axios 文件中?这主要是我项目中的文件

这是我的 AuthController 代码

 $remember_token = $user->createToken('remember_token',expiresAt:now()->addMinute())->plainTextToken;

这是我的Login.jsx

   const onSubmit = async (data, event) => {
   event.preventDefault(); // Prevent default form submission behavior
   setLoading(true);
   await csrf()
     try {
     const config = {
    headers: {
      "Content-type": "application/json",
    }
  };
  const postData = {
    email_address: data.email_address,
    password: data.password,
  };
  const response = await axios.post(
    LOGIN_URL,
    JSON.stringify(postData),
    config
  ); 

  const { remember_token, user, roles_name } = response.data;
  console.log(JSON.stringify(response?.data));
  
  const role_id = response?.data?.user?.role_id;

  setLoading(false);

  // Set the authenticated user state using setAuth from your useAuth hook
  setAuth({ user, remember_token, roles_name, role_id});

  const rolePath = role_id === 1  ? '/'  : role_id === 2 ? '/' : role_id === 3 ? 
  '/scholar-dashboard' : '/login';

  // Navigate the user to the intended route (from variable contains the intended route)
  navigate(rolePath);
  
} catch (err) {
  setLoading(false);
  if(err.response?.status === 422){
    setErrMsg('Email address and password are required');
  }
  else if(err.response?.status === 409){
    setErrMsg('Email Address already been taken');
  }
  else if(err.response?.status === 500){
    setErrMsg('Server Error');
  }
  else if (err.response?.status === 401) {
    setErrMsg('Login failed. Please check your credentials and try again.');
  }
  else{
    setErrMsg('Network error occurred. Please try again.');
  }
}

}

reactjs token access-token logout laravel-sanctum
1个回答
0
投票

创建一个用于配置 Axios 实例的文件。您可以包含一个拦截器来检查令牌过期的响应并注销用户。

示例(axiosConfig.js):

import axios from 'axios';
import { logout } from './auth';

const api = axios.create({
  baseURL: 'your_api_base_url',
 });

// Add a response interceptor
api.interceptors.response.use(
 (response) => response,
 (error) => {
// Check if the error is due to an expired token
if (error.response && error.response.status === 401) {
  // Log out the user when the token is expired
  logout();
  // You can also navigate to the login page here
  // Example: window.location.href = '/login';
}
return Promise.reject(error);
}
);

export default api;

这样,您可以将注销逻辑集中在Axios配置中,从而更易于管理和维护。当token过期后,任何使用axios发出的请求都会触发拦截器,导致自动注销。

© www.soinside.com 2019 - 2024. All rights reserved.