Laravel 8 REST API with Passport Authentication Tutorial Example

Laravel 8

Nicesnippets

8162

06-10-2020


Laravel 8 REST API with Passport Authentication Tutorial Example

Hi Guys,

In this tutorial,I will learn you how to use rest api with passport authentication in laravel 8.you can easy and simply use rest api with passport authentication in laravel 8.

Rest API is must be use when you are working with mobile application. when your application is prefer for web app and mobile app than you must have to create api for your mobile development.

However, Laravel provide easy way to create api. if you have authentication in your mobile app than you can easily do it using passport. Laravel 8 Passport provide way to create auth token for validating users.

Follow bellow few steps to create restful api example in laravel 8 app.

Step 1: Install Laravel 8


In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3: Use Passport

In this step we need to install passport via the Composer package manager, so one your terminal and fire bellow command:

composer require laravel/passport

After successfully install package, we require to get default migration for create new passport tables in our database. so let's run bellow command.

php artisan migrate

Next, we need to install passport using command, Using passport:install command, it will create token keys for security. So let's run bellow command:

php artisan passport:install

Step 4: Passport Configuration

In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.

In model we added HasApiTokens class of Passport,

In auth.php, we added api auth configuration.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable

{

use HasApiTokens, HasFactory, Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name',

'email',

'password',

];

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $hidden = [

'password',

'remember_token',

];

/**

* The attributes that should be cast to native types.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

}

After that, open app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function, It will evoke the required routes:

<?php

namespace App\Providers;

use Laravel\Passport\Passport;

use Illuminate\Support\Facades\Gate;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider

{

/**

* The policy mappings for the application.

*

* @var array

*/

protected $policies = [

'App\Model' => 'App\Policies\ModelPolicy',

];

/**

* Register any authentication / authorization services.

*

* @return void

*/

public function boot()

{

$this->registerPolicies();

}

}

config/auth.php

<?php

return [

.....

'guards' => [

'web' => [

'driver' => 'session',

'provider' => 'users',

],

'api' => [

'driver' => 'passport',

'provider' => 'users',

],

],

.....

]

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 5: Create API Routes

In this step, we will create api routes. Laravel provide api.php file for write web services route. So, let's add new route on that file.

routes/api.php

<?php

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\API\AuthController;

/*

|--------------------------------------------------------------------------

| API Routes

|--------------------------------------------------------------------------

|

| Here is where you can register API routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| is assigned the "api" middleware group. Enjoy building your API!

|

*/

Route::post('register', [AuthController::class, 'register']);

Route::post('login', [AuthController::class, 'login']);

Route::middleware('auth:api')->group(function () {

Route::get('get-user', [AuthController::class, 'userInfo']);

});

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {

return $request->user();

});

Step 7 – Creating API Auth Controller

In step 7, create import and export csv file controller by using the following command:

php artisan make:controller API\AuthController

The above command will create AuthController.php file, which is located inside LaravelPassportAuth/app/Http/Controllers/API directory. So add the following code into it:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\User;

class AuthController extends Controller

{

/**

* Registration Req

*/

public function register(Request $request)

{

$this->validate($request, [

'name' => 'required|min:4',

'email' => 'required|email',

'password' => 'required|min:8',

]);

$user = User::create([

'name' => $request->name,

'email' => $request->email,

'password' => bcrypt($request->password)

]);

$token = $user->createToken('Laravel8PassportAuth')->accessToken;

return response()->json(['token' => $token], 200);

}

/**

* Login Req

*/

public function login(Request $request)

{

$data = [

'email' => $request->email,

'password' => $request->password

];

if (auth()->attempt($data)) {

$token = auth()->user()->createToken('Laravel8PassportAuth')->accessToken;

return response()->json(['token' => $token], 200);

} else {

return response()->json(['error' => 'Unauthorised'], 401);

}

}

public function userInfo()

{

$user = auth()->user();

return response()->json(['user' => $user], 200);

}

}

Now we are ready to to run full restful api and also passport api in laravel. so let's run our example so run bellow command for quick run:

php artisan serve

make sure in details api we will use following headers as listed bellow:

'headers' => [

'Accept' => 'application/json',

'Authorization' => 'Bearer '.$accessToken,

]

Here is Routes URL with Verb:

Now simply you can run above listed url like as bellow screen shot:

1) Register API: http://localhost:8000/api/register

2) Login API: http://localhost:8000/api/login

I hope it can help you...


Recommended Posts