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:
Install Laravel Sanctum:
bashcomposer require laravel/sanctum
Publish Configuration and Run Migrations:
bashphp artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
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.
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).
Update App\Http\Kernel.php
:
Add \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class
to the $middlewareGroups['web']
array.
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');
Create Controllers: Create controllers for user actions and authentication.
Generate API Tokens:
Update your User
model to use the HasApiTokens
trait:
phpuse Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Install Axios:
bashnpm install axios
Create Auth Service: Create a service to handle authentication requests using Axios.
Handle Login: Implement a login form and use the Auth Service to make a POST request to the Laravel Sanctum login endpoint.
Handle Logout: Implement a logout button or mechanism and use the Auth Service to make a POST request to the Laravel Sanctum logout endpoint.
Fetch User Information:
Implement a function to fetch user information from the Laravel Sanctum /user
endpoint.
Protect Routes: Use React Router to protect routes that require authentication. Redirect unauthenticated users to the login page.
Persist Authentication State: Use browser storage (localStorage or sessionStorage) or React context to persist authentication state between page refreshes.
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.