Laravel 9 rest api with passport authentication tutorial

Laravel 9 rest api with passport authentication tutorial

When building a mobile application, you need to create APIs to provide data to mobile app developers. Laravel 9 rest api with passport authentication tutorial a popular framework today, is primarily favored for its ability to create APIs. However, if you're new and don't understand what APIs and web services are, don't worry, this is the place for you. In this article, we'll guide you through creating APIs and performing authentication in the simplest way.

What is Passport?

Passport is a tool used in Laravel for API authentication. In Laravel, authentication through login forms is already integrated, but when it comes to handling APIs, tokens are often used to authenticate users and do not maintain session between requests. Laravel uses Laravel Passport to handle API authentication, providing a full OAuth2 server that allows you to deploy your application in just a few simple steps. Passport is built on top of the League's OAuth2 server, with the main author being Alex Bilbie.

Step 1: Create a Laravel Project

First, let's create a new Laravel project with the following command:

composer create-project --prefer-dist laravel/laravel rest-passport 

Step 2: Install Package

Next, install the Laravel Passport package with Composer:

composer require laravel/passport 

After successful installation, open the config/app.php file and add Passport's Service Provider to the providers section:

'providers' =>[
     Laravel\Passport\PassportServiceProvider::class,
],

Step 3: Run Migration and Installation

After registering the Service Provider, we'll create tables in the database by running the Migration command:

php artisan migrate 

Then, install Passport using the following command:

php artisan passport:install 

Step 4: Configure Passport

Configure Passport in the Laravel application. Open the app/User.php file and add the HasApiTokens trait to the User model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, 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',
    ];
}

Next, in app/Providers/AuthServiceProvider.php, register Passport's routes:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

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();
        Passport::routes();
    }
}

Finally, configure Passport in config/auth.php:

<?php
return [
...
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
...
];

Step 5: Create API Routes

In this step, we'll create API routes. Open the routes/api.php file and define the API routes for your application:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| 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::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('login', 'api\UserController@login');
Route::post('register', 'api\UserController@register');
Route::group(['middleware' => 'auth:api'], function() {
    Route::post('details', 'api\UserController@details');
});

Step 6: Create the Controller

Finally, we'll create the UserController to handle API requests. Use the following Artisan command:

php artisan make:controller API/UserController 

To test the Details API, you need to set the following headers:

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class UserController extends Controller
{
    public $successStatus = 200;

    /**
     * login api
     *
     * @return \Illuminate\Http\Response
     */
    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
                ],
                $this->successStatus
            );
        }
        else {
            return response()->json(
                [
                    'error' => 'Unauthorised'
                ], 401);
        }
    }

    /**
     * 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 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
            ],
            $this->successStatus
        );
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function details()
    {
        $user = Auth::user();

        return response()->json(
            [
                'success' => $user
            ],
            $this->successStatus
        );
    }
}

Conclusion

So we've completed the tutorial for today. It's been a while since I've dived back into Laravel, and this is a great opportunity to refresh the basics. Hopefully, through this article, newcomers or those exploring Passport will have a clearer understanding and know how to apply it in their projects.

Thank you for taking the time to read my article!