Laravel 9 REST API with Passport Authentication Tutorial

Laravel 9 REST API with Passport Authentication Tutorial

 Laravel 9 REST API with Passport Authentication Tutorial

Hello, Teams,

I will show you how to work with the Laravel 9 Passport  API authentication example. you will learn Laravel 9 rest API using Passport. you can see the Laravel 9 Passport  API example. you can see the Laravel 9 Passport  API example.

Laravel 9 Passport provides a simple authentication system for SPAs (single-page applications), mobile applications, and simple, token-based APIs. Passport also allows each user of your application to generate multiple API tokens for their account.

If you also want to create an API for your mobile application then you can follow this tutorial to create the rest API step by step with Laravel 9 and Passport. If you are new then don't worry about that I wrote the tutorial step by step.
Follow bellow few steps below to create a restful API example in the Laravel 9 app



  • Step 1: Install Laravel 9 App
  • Step 2: Configure the Database with the App
  • Step 3: Install Passport Auth
  • Step 4: Passport Configuration
  • Step 5: Run Migration
  • Step 6: Create APIs Route
  • Step 7: Create a Passport Auth Controller
  • Step 8: Now Test Laravel REST API in Postman

Step 1: Install Laravel 9

First of all, Open a command prompt and run the following command to install the Laravel 9 app:

composer create-project laravel/laravel example_api_passport

Step 2: Install Passport

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

composer require laravel/passport

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


php artisan passport:install

we require default migration to create new sanctum tables in our database. so let's run the below command.

php artisan migrate

Step 3: Passport Configuration

In this step, we have to configure three place models, service providers, and auth config files. So you have to just make the following change on that file.

In the model, we added the 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\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

config/auth.php

<?php

return [
    .....
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    .....
]

Step 4: Create API Routes

In this step, we will create API routes for login, register and products rest api. So, let's add a new route to that file.

routes/api.php

<?php
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\ProductController;
  
/*
|--------------------------------------------------------------------------
| 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', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
     
Route::middleware('auth:api')->group( function () {
    Route::resource('products', ProductController::class);
});


Step 5: Create Controller Files

in the next step, now we created new controllers as BaseController, ProductController, and RegisterController, I created a new folder "API" in the Controllers folder because we will make alone APIs controller, So let's create both controllers:

app/Http/Controllers/API/BaseController.php

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;

class BaseController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendResponse($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];
        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];

        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }
        return response()->json($response, $code);
    }
}

app/Http/Controllers/API/RegisterController.php

<?php
   
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
   
class RegisterController extends BaseController
{
    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->accessToken;
        $success['name'] =  $user->name;
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}


Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your postman and check the following API.

make sure in details API we will use the following headers as listed below:

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
]

Here is Routes URL with Verb:

Now simply you can run the above-listed URL as below screenshot:

1) Register API: Verb:GET, URL:http://localhost:8000/api/register




2) Login API: Verb:GET, URL:http://localhost:8000/api/login




I hope it can help you more.
Reactions

Post a Comment

0 Comments

close