Posts Tagged ‘OAuth2’

Make an OAuth2 server using Laravel Passport

Tuesday, November 3rd, 2020

Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests.

Laravel Passport is a native OAuth 2 server for Laravel apps. Laravel Passport package comes with database migrations, routes, and middleware to ultimately create an authorization server that will return access tokens to allow access to server resources. It uses the League OAuth2 Server package as a dependency but provides a simple, easy-to-learn, and easy-to-implement syntax.

The source code to the todo application is available on GitHub.

This is not an OAuth or Laravel tutorial, so this article will focus solely on how you can use Laravel Passport to create an OAuth server on an existing application. If you want to learn more about Laravel or OAuth, you can look here and here respectively.

Installation/ Requirements

Before we start setting up, make sure you have the following requirements ready as they will be necessary to follow through this article:

Step-1. Getting Started

Let’s go ahead and create a brand new Laravel project first of all. Open your Terminal or Command Prompt and go to the directory where you want to create an app. You can use the following command to change directory.

First of all install the composer in your system and this command.

$ composer install

Use command to change directory.

$ cd Desktop/

Then, run the following command to create a new project.

$ composer create-project --prefer-dist laravel/laravel auth-app

Next, go inside the directory by running this command.

$ cd auth-app/

Run migration Database.

$ php artisan migrate

Generate a secure application key.

$ php artisan key:generate

Now, run your project after install successfully using this command on the terminal.

$ php artisan serve

Now, you get?http://127.0.0.1:8000?to click it and you see Laravel homepage.

Step-2. Installing Laravel Passport

Now let?s install Laravel Passport as well by running the following command.

composer require Laravel/passport

Step-3. Migrate Database

After Passport service provider registers, we require to run the migration command, after running the migration command you will get several new tables in the database. So, let?s run below command:

$ php artisan migrate

Create a User table

bigincrements(?id?);
          $table->string(?first_name?);
          $table->string(?last_name?);
          $table->string(?email?)->unique();
          $table->timestamp(?email_verified_at?)->nullable();
          $table->string(?password?);
          $table->rememberToken();
          $table->timestamps();
      });
  }
  public function down()
  {
       Schema::dropIfExists(?users?);
  }
}

At .env file we have to manage database configuration.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Database
DB_USERNAME=Username
DB_PASSWORD=Password

Step-4. Passport Configuration at our project

In this step, we have to do the configuration on three place Model, Service provider, and config/auth.php file.

So you have to just follow the change on that file.

In the User model: We added Laravel\Passport\HasApiTokens trait,

In app/Providers/AuthServiceProvider.php call Passport::routes

?App\Policies\Modelpolicy?
       ];
   Public function boot()
     {
     $this->registerPolicies();
     passport::routes();
}
}

In auth.php, we added an API auth configuration.

[
        ?guard? => ?web?,
        ?passwords? => ?users?,
    ],
    ?guards? => [
        ?web? => [
            ?driver? => ?session?,
            ?provider? => ?users?,
      ],
      ?api? => [
          ?driver? => ?passport?,
          ?provider? => ?users?,
       ],
   ],
   ?providers? => [
       ?users? => [
           ?driver? => ?eloquent?,
   ?model? => App\User::class,
        ],
    ],
    ?password? => [
       ?users? => [
        ?provider? => ?users?,
        ?table? => ?password_resets?,
        ?expire? => 60,
    ],
  ],
];

Step-6. Set API routes

Create all our routes in routes/api.php.

?auth?
], function () {
      Route::post(?login?, ?Auth\[email protected]?)->name(?login?);
      Route::post(?register?, ?Auth\[email protected]?);
      Route::group([
         ?middleware? => ?auth:api?
       ], function() {
           Route::get(?logout?, ?Auth\[email protected]?);
           Route::get(?user?, ?Auth\[email protected]?);
    });
});

Step-7. Create Controller

Now we need to create AuthController. Run the following command.

$ php artisan make:controller Auth/AuthController

Then, open AuthController.php and add this code.

In this code, we make 3 functions.

  1. Register Users
  2. Login users
  3. Logout
validate([
             ?email? => ?required|string|email?,
             ?password? => ?required|string?
           ]);
        $credentials = request([?email?, ?password?]);
     // print_r($credentials);die;
     if(!Auth::attempt($credentials))
         return response()->json([
            ?message? => ?Unauthorized?
         ],401);
     $user = $request->user();
     $tokenResult = $user->createToken(?Personal Access Token?);
     $token = $tokenResult->token;
     if ($request->remember_me)
         $token->expires_at = Carbon::now()->addWeeks(1);
     $token->save();
     return response()->json([
         ?access_token? => $tokenResult->accessToken,
         ?token_type? => ?Bearer?,
         ?expires_at? => Carbon::parse(
             $tokenResult->token->expires_at
          )->toDateTimeString()
      ]);
   }
   public function register(Request $request)
   {
          $request->validate([
                 ?fName? => ?required|string?,
                 ?lName? => ?required|string?,
                 ?email? => ?required|string|email|unique:users?,
                 ?password? => ?required|string?
          ]);
          $user = new User;
          $user->first_name = $request->fName;
          $user->last_name = $request->lName;
          $user->email = $request->email;
          $user->password = bcrypt($request->password);
          $user->save();
          return response()->json([
               ?message? => ?Successfully created user!?
          ], 201);
   }
   public function logout(Request $request)
   {
        $request->user()->token()->revoke();
        return response()->json([
          ?message? => ?Successfully logged out?
}
public function user(Request $request)
{
            return response()->json($request->user());
}
}

Step-8. Now Adding CORS Middleware

Run the following command to create a new Middleware.

$ php artisan make:middleware Cors
header(?Access-Control-Allow-Origin?, ?*?)
         ->header(?Access-Control-Allow-Methods?,
                   ?GET, POST, PUT, PATCH, DELETE, OPTIONS?)
         ->header(?Access-Control-Allow-Headers?,
                  ?Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN?);
}
}

Step-9. Register new middleware in app/Http/Kernal.php.

Finally, Run the following command to run.

$ php artisan passport:install
$ php artisan serve

Tests

Now time to test the whole things are working properly or not, if you get an error please follow all these steps again.

We are simply tested by rest-client tools.

For Register New Users

Sending First Name, Last Name, Email, and Password in POST requests.

Now log in with your register email and password.

When you log in with register email and password you got token. You can store this token in local storage. This token is also stored in the oauth_access_tokens table.

We will be sending a GET request to your URL and we need to send it token as Authorization Header.

Conclusion

Above way we can do API authentication in Laravel Application with a passport. Laravel Passport makes it super easy and it takes only a few steps as we have seen in the article to make your application OAuth2 enabled. If you get any errors, please follow the steps again.

Recent Posts

Recent Comments

Get In Touch

Ask Us Anything !

Do you have experience in building apps and software?

What technologies do you use to develop apps and software?

How do you guys handle off-shore projects?

What about post delivery support?