There are many ways to authenticate api in Laravel like sessions, jwt tokens.
Passport is a Laravel package that came up with Laravel 5.3 to authorise the external request. For example, accessing the data using API calls from the android or IOS mobile applications.
There are some protected APIs in the application that requires access token to authenticate the request because API do not maintain session state between requests. In this example, I will let you know how to get access token after user authentication via API and how will you use the access token to access a protected resource from the API.
To get access token, you must login with user credentials within the application using API.Laravel Installation and Passport package configuration
In this first step, You will have to setup your application. Run following command using composer to get fresh Laravel application.
composer create-project --prefer-dist laravel/laravel blog "5.5.*"
To get started with Passport, you will have to require
laravel/passport package with the help of composer.
composer require laravel/passport
After successfully installing the package, you will need to register the Laravel Passport service provider in the providers array of
'providers' => [ .... Laravel\Passport\PassportServiceProvider::class, ], ....
After register the passport service provider, you must migrate your database because it register its own database migration directory.
Run following command to migrate the database :
php artisan migrate
This will create the tables in your database to save access token of authorized users.
Next, we will run the
passport:install command to create the encryption keys that will use to generate secure access tokens.
php artisan passport:install
After running above command, add the
HasApiTokens trait to the
Next, edit the AuthServiceProvider and call
Passport::routes method within the
Finally let's update the drive in
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],Add routes
Now Passport configuration has been completed. So let's start with the passport authentication process by adding following routes for APIs.routes/api.php Create UserController.php within the Api directory
In this last step, We will create a directory "Api" within the app/Http/Controllers directory and create a UserController.php inside it.app/Http/Controllers/Api/UserController.php
Now you are ready to authenticate API using passport in Laravel.Login API
User Details API
Now to get the user details, you will have to pass access token via header :
'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer '.$accessToken, ]