Skip to content

Creating a Laravel with Passport Api with React boilerplate

Notifications You must be signed in to change notification settings

silvicardo/laravel-passport-react

Repository files navigation

Build Status Total Downloads Latest Stable Version License

Passport Steps

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',
    ],
],

AuthController

Create your new controller:

php artisan make:controller Api/AuthController.php

ForceJsonResponse Middleware

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,

Routes

All routes will use ForceJsonResponse middleware, protected ones also use 'auth:api'

Postman testing

Set Headers:

Content-Type: application/json
X-Requested-With: XMLHttpRequest

Getting Started

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

Prerequisites

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.

Built With

  • Laravel - The PHP Framework For Web Artisans
  • React - A JavaScript library for building user interfaces
  • React-Redux - Official React bindings for Redux

About

Creating a Laravel with Passport Api with React boilerplate

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published