How to handle user authentication using Laravel Sanctum and ReactJS



Image not found!!

Handling user authentication with Laravel Sanctum and ReactJS involves a combination of server-side and client-side code. Laravel Sanctum is a package that provides a simple API for handling authentication, especially for SPAs (Single Page Applications) like those built with ReactJS. Below are the steps to set up user authentication using Laravel Sanctum and ReactJS:

Server-Side (Laravel Sanctum):

  1. Install Laravel Sanctum:

    bash
    composer require laravel/sanctum
  2. Publish Configuration and Run Migrations:

    bash
    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
    php artisan migrate
  3. Update config/cors.php: Ensure your config/cors.php file allows requests from your ReactJS app by adding your React app's URL to the paths array.

  4. Configure Sanctum: In your config/sanctum.php file, update the stateful option to include routes that should be considered stateful (e.g., routes that should keep the user authenticated).

  5. Update App\Http\Kernel.php: Add \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class to the $middlewareGroups['web'] array.

  6. Create API Routes: Create routes for login, logout, and user information. For example:

    php
    // routes/api.php Route::middleware('auth:sanctum')->group(function () { Route::get('/user', 'UserController@index'); Route::post('/logout', 'AuthController@logout'); }); Route::post('/login', 'AuthController@login');
  7. Create Controllers: Create controllers for user actions and authentication.

  8. Generate API Tokens: Update your User model to use the HasApiTokens trait:

    php
    use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; }

Client-Side (ReactJS):

  1. Install Axios:

    bash
    npm install axios
  2. Create Auth Service: Create a service to handle authentication requests using Axios.

  3. Handle Login: Implement a login form and use the Auth Service to make a POST request to the Laravel Sanctum login endpoint.

  4. Handle Logout: Implement a logout button or mechanism and use the Auth Service to make a POST request to the Laravel Sanctum logout endpoint.

  5. Fetch User Information: Implement a function to fetch user information from the Laravel Sanctum /user endpoint.

  6. Protect Routes: Use React Router to protect routes that require authentication. Redirect unauthenticated users to the login page.

  7. Persist Authentication State: Use browser storage (localStorage or sessionStorage) or React context to persist authentication state between page refreshes.

  8. Handle Token Expiry: Implement a mechanism to handle token expiry and refresh the token when needed.

Here's a simplified example of how a login function in a React component might look:

jsx
// Example Login Component import React, { useState } from 'react'; import authService from './services/authService'; const Login = () => { const [credentials, setCredentials] = useState({ email: '', password: '' }); const handleLogin = async () => { try { const response = await authService.login(credentials); console.log(response.data); // Handle successful login } catch (error) { console.error(error.response.data); // Handle login error } }; return ( <div> <input type="email" placeholder="Email" onChange={(e) => setCredentials({ ...credentials, email: e.target.value })} /> <input type="password" placeholder="Password" onChange={(e) => setCredentials({ ...credentials, password: e.target.value })} /> <button onClick={handleLogin}>Login</button> </div> ); }; export default Login;

Ensure you handle errors appropriately, manage token storage securely, and implement other necessary features based on your application's requirements.