This is an example to create SPA authentication using the Laravel Sanctum with the front-end framework used is ReactJS. This repos just for practice, not for production method because I don't know whether my method is proven to be very safe or not. I also just learned React JS and Laravel here recently. So if something is not in accordance with the existing rules, I am sorry.
- Laravel UI for generate basic scaffolding React JS and Auth.
- Laravel Sanctum.
- React Reveal (For testing only, you can remove the component at App.js and uninstall it).
- React Redux.
- Redux.
- React Toastify (For testing only, you can uninstall it).
- Node JS
This is just for one server with back-end and front-end. Don't forget to command at the project folder:
npm install
and
npm run dev
-
Laravel is already installed (For Mac it is recommended to install Laravel Valet for easy configure and many feature you will like!)
-
The Node JS has been installed
-
Prepare a new laravel project and set the db settings in .env
-
Execute command:
composer require laravel / ui
php artisan ui react --auth
composer require laravel / sanctum
-
.env settings that need to be added
SESSION_DOMAIN = .sikbantul.test //(Server domain name)
SESSION_DRIVER = cookie
SANCTUM_STATEFUL_DOMAINS = sikbantul.test //(SPA domain name)
-
In app / http / kernel.php add in the array of api above the throttle
EnsureFrontendRequestsAreStateful :: class,
-
In the sanctum.php config section in the SANCTUM_STATEFUL_DOMAINS section add something like no.6 sikbantul.test to take care when it does happen unauthicated continuously.
-
In the cors.php config, configure something like this:
'paths' => [ 'api/*', '/login', '/logout', '/sanctum/csrf-cookie' ],
and
supports_credentials' => true,
-
Add the configuration below window.axios ... in bootstrap.js
axios.defaults.withCredentials = true;
-
Create a LoginController
(Example: https://github.com/herlandroando/laravelSanctum-testingauth/blob/master/app/Http/Controllers/Api/LoginController.php) -
Set the ReactJS rendering on a single blade page by creating a file app.blade.php
(Example: https://github.com/herlandroando/laravelSanctum-testingauth/blob/master/resources/views/app.blade.php) -
For the rest front-end, see https://github.com/herlandroando/laravelSanctum-testingauth/tree/master/resources/js