Laravel 9 REST API with Passport Authentication Tutorial

By Sumeet Shroff
Last Updated On : February 10, 2023
Laravel 9 REST API with Passport Authentication Tutorial

Laravel is a popular PHP framework that makes it easier for developers to build robust and secure web applications. In this tutorial, we will be building a REST API in Laravel 9 that uses Passport for authentication. Before we dive into the tutorial, let's go over what a REST API is and what Passport does. A REST API (Representational State Transfer API) is a web API that uses HTTP methods like GET, POST, PUT, DELETE to interact with data. Passport is a Laravel package that makes it easy to implement OAuth2 authentication in your application. Now, let's get started.

Step 1: Install Laravel 9

To install Laravel 9, you will need to have Composer installed on your machine. Once you have Composer installed, open a terminal and run the following command:

composer create-project --prefer-dist laravel/laravel laravel9-rest-api

Step 2: Install Passport

To install Passport, run the following command in your terminal:

composer require laravel/passport

Step 3: Run Migrations

Next, we need to run migrations to create the necessary tables in the database. Run the following command in your terminal:

php artisan migrate

Step 4: Create Client IDs and Secrets

We need to create client IDs and secrets for our API. Run the following command in your terminal to create the clients:

php artisan passport:client

Step 5: Configure Passport

Now, we need to configure Passport. First, we need to add the following code to the config/auth.php file:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Next, we need to add the following code to the app/Providers/AuthServiceProvider.php file:

use Laravel\Passport\Passport;
public function boot()
{
    $this->registerPolicies();
    Passport::routes();
}

Step 6: Define Models and Controllers

Next, we need to define the models and controllers for our API. First, let's create a User model. Run the following command in your terminal:

php artisan make:model User -m

Then, add the following code to the app/User.php file:

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Next, let's create a controller for our API. Run the following command in your terminal:

php artisan make:controller API/UserController

7: Define API Routes

Next, we need to define the API routes for our application. Add the following code to the routes/api.php file:

Route::post('register', 'API\UserController@register');
Route::post('login', 'API\UserController@login');
Route::middleware('auth:api')->group(function(){
    Route::get('user', 'API\UserController@details');
});

Step 8: Implement User Registration and Login

Now, we need to implement user registration and login in the UserController. Add the following code to the app/Http/Controllers/API/UserController.php file:

use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
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 response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] = $user->createToken('MyApp')->accessToken;
    $success['name'] = $user->name;
    return response()->json(['success'=>$success], 200);
}
public function login()
{
    if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
        $user = Auth::user();
        $success['token'] = $user->createToken('MyApp')->accessToken;
        return response()->json(['success' => $success], 200);
    }
    else{
        return response()->json(['error'=>'Unauthorized'], 401);
    }
}

Step 9: Implement User Details

Finally, we need to implement the user details endpoint. Add the following code to the app/Http/Controllers/API/UserController.php file:

public function details()
{
    $user = Auth::user();
    return response()->json(['success' => $user], 200);
}

That's it! You have successfully built a REST API in Laravel 9 that uses Passport for authentication. You can test the API using Postman or any other API testing tool. In conclusion, Laravel makes it easy for developers to build secure and robust web applications. With the help of Passport, implementing OAuth2 authentication in your laravel application is a breeze. I hope you found this tutorial helpful.

Categories

Latest Blogs

Ready to Amplify Your Services with our Premium White Label Web Design

Are you looking to expand your service offerings without the overhead of an in-house design team? Our white label web design services are the perfect solution. We provide top-notch, fully customizable web designs that seamlessly blend with your brand, allowing you to offer additional value to your clients.
Contact Us Today to Start Partnering with Our White Label Web Design Experts!

We love to provide services in the following cities

© 2024 · Prateeksha Web Design. Built with Gatsby All rights reserved | Privacy Policy
Designed by Prateeksha Web