Create API Authentication with Laravel Passport

Sumit Talwar · · 7575 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\AuthController@login');
	 Route::post('signup', 'Auth\AuthController@signup');
});
	 
Route::group(['middleware' => 'auth:api'], function () {
	 Route::get('user', 'Auth\AuthController@user');
	 Route::get('logout', 'Auth\AuthController@logout');
});

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:

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar

PHP Generators: Efficient Data Handling and Iteration Techniques

PHP Generators offer a powerful and memory-efficient way to handle large datasets and complex iteration scenarios in your applications. They provide a more elegant solution compared (...)
Harish Kumar