Laravel Passport API Authentication Tutorial Example

laravel passport, laravel faker, laravel elasticsearch, install laravel on windows, laravel scout search, laravel pagination search

You will learn to create Laravel Passport API Authentication Example.

REST API are used to make the data transmission between the database and mobile device.

For example, when user make registration process from mobile app, REST API will help us to store the user details like username, password, email etc. to the database.

Laravel have package called “Passport” which enables OAuth Authentication by generating the token.

We will make one web app which will create three REST APIs.

One is for Registration, one is for Login and last is for fetching the user data from database.

Look at the below output video for more reference.

Now follow all the below steps to create Passport API Authentication in Laravel.

Move 1. New Laravel Project

Go to your terminal or the command prompt and hit the below command

composer create-project laravel/laravel=7 laraPassport --prefer-dist

Above command will help you to create the Laravel 7 project.

Now open up your project in editor tool. I am using Visual Studio code.

Navigate to your .env file. In this file, see the below lines

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraPassport
DB_USERNAME=root
DB_PASSWORD=

Above lines are useful to connect our laravel project with the MySQL Database.

Before you update the above lines, make sure that you have manually created a database with name “laraPassport” in the dashboard of your MySQL admin.

I am using Sequel pro to maintain database. If you are using phpMyAdmin or something else then it is also good.

After creating database, set the username and password in the above lines.

Move 2. Adding Passport Package

Again go to your terminal or command prompt and run the following command

composer require laravel/passport

Above line will download required files to use the Passport package in our web application.

Now navigate to the Config/app.php file in your laravel project.

In this Config/app.php file, add the line “Laravel\Passport\PassportServiceProvider::class,” in “providers

 'providers' => [
        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        ...
        ...
        ...
        Laravel\Passport\PassportServiceProvider::class,

Move 3. Passport Installation

Now again go to your terminal or command prompt and run the following command

php artisan migrate

Above command will create few tables in our database. These tables will help us to create authentication system.

Now hit the below command in the terminal

php artisan passport:install

Above line will install the required files of the Passport package in our project.

Now go to app->User.php file and add two below lines in this file.

 "Laravel\Passport\HasApiTokens;" 
use HasApiTokens, Notifiable;

So final source code for app->User.php file is as the following

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Move 4. Authentication Files

Navigate to the app->Providers->AuthServiceProvider.php file and add the following line in it

use Laravel\Passport\Passport;

So the final code snippet for AuthServiceProvider.php file is as the below

<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
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();
        //
    }
}

In the above file, make sure that you have added the line “use Laravel\Passport\Passport;”

Now go to config->auth.php file and use “guards” and “api” array as the below

  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],

Move 5. Making Routes

Now navigate to the routes->api.php file and write down the following coding lines in it

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::group(['middleware' => 'auth:api'], function(){
	Route::post('getRegisteredUser', 'API\UserController@getRegisteredUser');
});

As you can see in the above code that we have added three routes : login, register and getRegisteredUser.

Move 6. Writing Controller

Again use the below command to create the controller file.

php artisan make:controller API/UserController

Above file will make the controller file. Go to app/Http/Controllers/API/UserController.php and add the following code lines in it

<?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);
    }
    /**
     * getRegisteredUser api
     *
     * @return \Illuminate\Http\Response
     */
    public function getRegisteredUser()
    {
        $user = Auth::user();
        return response()->json(['success' => $user], $this->successStatus);
    }
}

When you hit the API “http://127.0.0.1:8000/api/register” (Register API) , compiler will run the register() function from the above file.

Similarly, for login API (http://127.0.0.1:8000/api/login) compiler will call the login() method.

For API (http://127.0.0.1:8000/api/getRegisteredUser) , compiler will go through the method getRegisteredUser()

Our all the tasks related to coding is complete.

Now hit the following command to run our project.

php artisan serve

Now to test the passport api and to generate the passport api token, you need to run the API in Rest client like postman or other.

For accessing getRegisteredUser API, you have to pass the below headers

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

Here, $accessToken is the token created when you run the login or register API.

You should see the output video to have more reference regarding token generation.

Download Source Code From Github

Click to go to the Github for Source code