Hi there!
Your approach is indeed valid. Laravel Fortify is a backend authentication package for Laravel that provides features like login, registration, email verification, two-factor authentication, session management, and password reset. It's designed to work with Laravel's server-rendered blade templates out of the box.
On the other hand, Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account, which may be granted abilities/scopes.
Here's a step-by-step breakdown of how you can implement your plan:
1. Install Laravel Fortify and set it up for your login, registration, and password reset. You can publish the Fortify views and customize them as needed.
2. Install Laravel Sanctum and configure it according to the documentation. Make sure to configure your `config/sanctum.php` and `config/cors.php` properly to allow your SPA to communicate with your Laravel app.
3. After a user logs in using Fortify, redirect them to your dashboard route which serves your React SPA.
4. In your React application, use Axios for making XHR requests to your API. Ensure that you are sending the `XSRF-TOKEN` cookie and the `Authorization` header with the Bearer token if you are using Sanctum's token-based authentication.
5. Protect your API routes using Sanctum's middleware. You can do this by adding the `auth:sanctum` middleware to your API routes in your `routes/api.php` file.
Here's an example of how you might set up your API routes:
```php
// routes/api.php
use Illuminate\Http\Request;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
// Other protected routes...
And here's an example Axios request from your React app:
// Example Axios request in React component
axios.get('/api/user', {
withCredentials: true // This is important to include credentials/cookies
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
Make sure your SPA is able to access the CSRF token and that you're including credentials with your requests (withCredentials: true).
By following these steps, you should have a secure authentication system using Laravel Fortify for your blade views and Laravel Sanctum for your SPA.
Good luck with your project!