Create API Authentication with Laravel Passport

Sumit Talwar · · 5280 Views

In this article, we'll see how to implement restful API authentication using Laravel Passport. You should have experience working with Laravel as this is not an introductory tutorial.

Step 1. Install Laravel

In the first step, we need to get a new Laravel application. So, run the following command in the terminal to create a new Laravel app:

composer create-project --prefer-dist laravel/laravel app-name

Step 2. Install and Setup Laravel Passport

To install Laravel Passport, run the following command:

composer require laravel/passport

Now, run the following command to migrate Laravel Passport tables. The Passport migrations will create some new tables for storing the tokens.

php artisan migrate

Next, we need to create encryption keys. These keys are needed for generating the access token. Run the following command to install the encryption keys:

php artisan passport:install

Next, add the Laravel\Passport\HasApiTokens trait to your User model. This trait will give a couple of helper methods to your model which permit you to assess the authenticated user's token and scopes:

<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;
}

Next, you need to call the Passport::routes method inside the boot method of your AuthServiceProvider. This method will register the routes necessary to issue tokens and revoke access tokens, clients, and personal access tokens:

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

The final configuration is, in your config/auth.php file, you need to change the driver option of the api authentication guard to passport. This will instruct your application to utilize Passport's TokenGuard while authenticating incoming API requests:

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

Step 3. Create API Routes

Now, open the route/api.php and create authentication API routes:

Route::group(['prefix' => 'auth'], function(){
	 Route::post('login', 'Auth\[email protected]');
	 Route::post('signup', 'Auth\[email protected]');
});
	 
Route::group(['middleware' => 'auth:api'], function () {
	 Route::get('user', 'Auth\[email protected]');
	 Route::get('logout', 'Auth\[email protected]');
});

Step 4: Create AuthController

All right, let’s create the authentication controller now.

php artisan make:controller Auth\AuthController

Next, open the AuthController.php and add the following snippet:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
class AuthController extends Controller
{
    /**
     * Create user
     *
     * @param  [string] name
     * @param  [string] email
     * @param  [string] password
     * @param  [string] password_confirmation
     * @return [string] message
     */
    public function signup(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed'
        ]);
        $user = new User([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
        $user->save();
        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }
  
    /**
     * Login user and create token
     *
     * @param  [string] email
     * @param  [string] password
     * @param  [boolean] remember_me
     * @return [string] access_token
     * @return [string] token_type
     * @return [string] expires_at
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        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()
        ]);
    }
  
    /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }
  
    /**
     * Get the authenticated User
     *
     * @return [json] user object
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}

Let’s try it!

Alright, so we have configured all necessary preparations for implementing the Passport API authentication.

Now, we can simply test this in the rest-client tools (Postman). You can see the below screenshots.

In this API you have to set two headers as listed below:

Content-Type: application/json
X-Requested-With: XMLHttpRequest
Create API Authentication with Laravel Passport
0

Please login or create new account to add your comment.

0 comments
You may also like:

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar

Mobile App Development Process

With businesses adopting a mobile-first approach and the growing number of mobile apps, successful mobile app development seems like a quest. But it’s the process that determines (...)
Narola Infotech

What are Laravel Macros and How to Extending Laravel’s Core Classes using Macros with example?

Laravel Macros are a great way of expanding Laravel's core macroable classes and add additional functionality needed for your application. In simple word, Laravel Macro is an (...)
Harish Kumar