79163884

Date: 2024-11-06 18:50:52
Score: 0.5
Natty:
Report link
  1. Login: Generate and Store the Token On the React frontend, log in and store the token

  2. Token Verification and Auto-Logout Use Axios interceptors in React to catch 401 Unauthorized responses globally. This way, if the token is expired or invalid, you can automatically log out the user and redirect them to the login page.

  3. Token Deletion on Logout In your Laravel API, use the logout function to revoke all tokens. When logging out on the frontend, clear the token from localStorage and remove it from Axios defaults.

  4. Token Expiration/Invalidation on Laravel With Laravel Sanctum, tokens do not expire by default. To achieve auto-expiration, you can:

Set a custom expiration time for tokens. Use a middleware to handle token expiration.

  1. React - Auto Logout on Expired Token When the backend sends a 401 Unauthorized response due to expiration, the Axios interceptor we set up earlier will handle it, logging the user out and redirecting them to the login page.

Complete Flow User logs in: The token is generated by Laravel and saved in the React frontend’s localStorage. User navigates protected routes: Axios sends the token with each request. Token verification: Laravel verifies the token; if it’s expired, it responds with a 401 Unauthorized. Auto logout on expiration: The Axios interceptor in React catches the 401 and logs the user out automatically. User logout: On manual logout, the token is removed from both the frontend and backend, ensuring it cannot be reused.

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Low reputation (1):
Posted by: TANISH SHARMA