Create API Authentication with Laravel Passport

Sumit Talwar · · 7125 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:

Compress and Download Files in Laravel Using ZipArchive with Examples

In web development, file compression is essential for optimizing data transfer and storage. Laravel provides tools for creating and downloading compressed files. This guide explores (...)
Harish Kumar

Implementing Multi-Authentication with Guards in Laravel

This guide provides a detailed explanation of how to implement multi-authentication using guards in a Laravel application. This is useful for applications that need to support (...)
Harish Kumar

Building Real-Time Chat Applications with Laravel Reverb and Vue 3

Real-time chat applications are increasingly important for seamless communication and instant connectivity. Laravel Reverb and Vue.js 3 provide developers with the tools to create (...)
Harish Kumar

Laravel Facades: Simplifying Code and Improve Readability

As an integral part of Laravel, a renowned PHP framework, Facades provide a static interface to classes stored in the application's service container. They serve as static proxies (...)
Harish Kumar

What is Laravel’s Service Container and How to Use Dependency Injection in Laravel App

Dependency injection and inversion of control are vital in clean web development. They make writing maintainable, testable code possible. Laravel is a famous PHP framework that (...)
Harish Kumar

Secure Your SPA with Laravel Sanctum: A Step-by-Step Guide

In today's web development landscape, Single Page Applications (SPAs) are increasingly popular. But securing their interaction with backend APIs is crucial. Laravel Sanctum provides (...)
Harish Kumar