Install the basic authentication system integrated in Laravel and Laravel Passport:
composer require laravel/passport
php artisan make:auth
php artisan migrate
php artisan passport:install
Add the Laravel\Passport\HasApiTokens trait to our App\User model:
<?php
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
?>
Add the Passport::routes method within the boot method of our app/AuthServiceProvider like that:
<?php
use Laravel\Passport\Passport;
...
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
?>
in config/auth set the driver option of the api authentication guard to passport like that:
<?php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Create your new controller:
php artisan make:controller Api/AuthController.php
Create your new middleware:
php artisan make:middleware ForceJsonResponse
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ForceJsonResponse
{
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
Add to the $routeMiddleware of the app/Http/Kernel.php file:
<?php
'json.response' => \App\Http\Middleware\ForceJsonResponse::class,
All routes will use ForceJsonResponse middleware, protected ones also use 'auth:api'
Set Headers:
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Clone the project repository by running the command below if you use SSH
git clone https://github.com/silvicardo/laravel-passport-react.git
If you use https, use this instead
git clone https://github.com/silvicardo/laravel-passport-react.git
After cloning, run:
composer install
npm install
Duplicate .env.example
and rename it .env
Then run:
php artisan key:generate
Be sure to fill in your database details in your .env
file before running the migrations:
php artisan migrate
And finally, start the application:
php artisan serve
and visit http://localhost:8000 to see the application in action.
- Laravel - The PHP Framework For Web Artisans
- React - A JavaScript library for building user interfaces
- React-Redux - Official React bindings for Redux