Categories

Monday, November 25, 2024
#919814419350 therichposts@gmail.com
Laravl 5.7

Create Rest Api Authentication in Laravel 5.7 Using Passport Package

Create Rest Api Authentication in Laravel 5.7 Using Passport Package - The Rich Post

Hello to all, welcome to therichpost.com. In this post, I will tell you, how to Create Rest Api Authentication in Laravel 5.7 Using Passport Package?

laravel api auth

 

API means Application Programming Interface which transfers data in two applications in Json format. In laravel, we create api’s for our mobile developers or get the data from other applications. APIs use tokens to authenticate users and do not maintain session between requests. In my previous posts, I did laravel api’s for Angular 6, React Js and Vue Js applications.

 

In this post, I will use Laravel Passport Package to create api auth and here is the full and easy process:

 

1. Very first, we need to install Laravel 5.7 Passport Package by run below command into your terminal:
composer require laravel/passport

 

2. After run above command, you need to add below code into your config/app.php file:
'providers' => [
                .... 
                Laravel\Passport\PassportServiceProvider::class,
                ....
               ],  

 

3. We need to run migration command to add Passport package table in our database:
php artisan migrate

 

4. After run above command, we will get below error in our terminal:

laravel migration error

 

5. To overcome this error, we need to update our app\Providers\AppServiceProvider file with below code:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

 

6. After done the above code, we need to again run the migrate command but first delete the users table from your database, otherwise, we can face again error:
php artisan migrate

 

7. After successfully run above command, you can see below tables in your database:

laravel migration tables

 

8. Next, we need to install passport with run below command into your terminal:

This will create security token keys:

php artisan passport:install

 

9. After run above command, we need to update app/User.php file with below code:
<?php

namespace App;

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

class User extends Authenticatable
{
    
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

 

10.  After, update your app/Providers/AuthServiceProvider.php file with below code:
<?php

namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    Passport::routes();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

 

11.  After it, above your config/auth.php with below code:
return [ 
        ..... 
        'guards' => 
                 [ 'web' => 
                         [ 'driver' => 'session',
                           'provider' => 'users', 
                         ], 
                   'api' => 
                          [ 'driver' => 'passport', 
                            'provider' => 'users', 
                          ], 
                 ], 
         .....
      ]

 

12.  Finally, we need to create our API’S Routes with below code in routes/api.php:
<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login', 'API\AuthController@login');
Route::post('register', 'API\AuthController@register');

 

13.  We need to create API Folder Into our app\Http\Controllers:

api folder

 

14. In app\Http\Controllers\API Folder, we need to create new file named AuthController.php file and add below code into this file:
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Support\Facades\Auth; 
use App\User; 
use Validator;
class AuthController extends Controller 
{
  /** 
   * Login API 
   * 
   * @return \Illuminate\Http\Response 
   */ 
  public function login(Request $request){ 
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
      $user = Auth::user(); 
      $success['token'] =  $user->createToken('LaraPassport')->accessToken; 
      return response()->json([
        'status' => 'success',
        'data' => $success
      ]); 
    } else { 
      return response()->json([
        'status' => 'error',
        'data' => 'Unauthorized Access'
      ]); 
    } 
  }
    
  /** 
   * Register API 
   * 
   * @return \Illuminate\Http\Response 
   */ 
  public function register(Request $request) 
  { 
    $validator = Validator::make($request->all(), [ 
      'name' => 'required', 
      'email' => 'required|email', 
      'password' => 'required', 
      'c_password' => 'required|same:password', 
    ]);
    if ($validator->fails()) { 
      return response()->json(['error'=>$validator->errors()]);
    }
    $postArray = $request->all(); 
    $postArray['password'] = bcrypt($postArray['password']); 
    $user = User::create($postArray); 
    $success['token'] =  $user->createToken('LaraPassport')->accessToken; 
    $success['name'] =  $user->name;
    return response()->json([
      'status' => 'success',
      'data' => $success,
    ]); 
  }
}

 

15. After all this, we need to test our’s api’s by downloading the postman software:

https://www.getpostman.com/apps

 

16.  Here I tested Register Api by enter name, email, password, and c_password. c_password details:

register api laravel

 

 

17. Here, I tested Login Api:

login laravel api

 

Now, we are done with Rest Api Authentication in Laravel 5.7 Using Passport Package . If you have any query related to this post, then do comment below or ask questions.

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

9 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.