Create API Authentication with Laravel Passport

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

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

Install Laravel Valet Linux+ development environment on Ubuntu System

The official Laravel Valet development environment is great if you are an Apple user. But there is no official Valet for Linux or Window system.
Harish Kumar

Laravel Sanctum API Token Authentication Tutorial with example

Laravel Sanctum is a popular package for API Token Authentication. There are many other packages available to authenticate the APIs request in Laravel. For example, We are already (...)
Harish Kumar

Create SPA authentication Using Laravel Sanctum and Vue.js

In this guide, we will focus on SPA authentication in a simple Vue.js app using Laravel Sanctum. Laravel Sanctum provides a featherweight authentication system for SPAs (single (...)
Harish Kumar

Laravel Themer: multi-theme support for Laravel application

This Laravel Themer package adds multi-theme support to your application. This theme package improves any application while allowing the freedom to organize and maintain your app's (...)
Harish Kumar

Difference between Laravel $request->input(), $request->get(), and $request->name direct property

If you’ve been around Laravel for a while, you might have seen there are three ways in controllers to retrieve inputs from the submitted form. For example, if you are trying (...)
Sohail