Laravel 8 Passport API Authentication


laravel application , API authentication के लिए कई driver जैसे sanctum / passport provide करता है , अपनी need के according इनमे से कुछ भी use कर सकते हैं।


इस topic में हम passport API Authentication package का use करके API Authentication system बनाएंगे जिसमे new user का registration / login और logut etc. होंगे।

Note : Laravel में REST Api बनाने से पहले हम या मानकर चलते हैं कि , आपको laravel की basic knowledge है , अगर नहीं तो आप हमरी website पर पढ़ सकते हैं।

Create Project

Api बनाने के लिए हम एक fresh laravel application install करेंगे।

composer create-project --prefer-dist laravel/laravel LaravelApiAuth

हमने एक नया project productapi बनाया है , जिसमे Products के लिए Api बनाएंगे।

Set Database

project install हो जाने के बाद आपको .env file में database credentials set करना है। जिससे आगे migrations बना सकें।

File : .env
-----------

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelapiauth
DB_USERNAME=root
DB_PASSWORD=

Install Passport API Package

Database credentials set करने के बाद अब Passport API Authentication package install करना है -

composer require laravel/passport
Run Migrate

इसके बाद required table के लिए migration run करना होगा जिससे database में tables बन सकें -

php artisan migrate
passport:install

migrate command run करने के बाद अगर आप database चेक करोगे तो कुछ tables बन जायँगी। Next हमें passport:install command run करनी है , यह command security के लिए token key create करेगी।

php artisan passport:install

Passport Configuration

अब हमें Passport package के according कुछ configurations करनी है तो सबसे पहले app / Providers / AuthServiceProvider.php के boot() method में जाकर changes करते हैं।

File : app / Providers / AuthServiceProvider.php

Copy Fullscreen Close Fullscreen
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        //passport routes
        if (! $this->app->routesAreCached()) {
            Passport::routes();
        }
    }
}

File : app / Models / User.php

Copy Fullscreen Close Fullscreen
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
File : config / auth.php
-------------------------------------------------------------------------

return [
    //change/add api driver only
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
]

Prepare API Routes

जैसा कि आपको पता है कि laravel application में Api के लिए सभी routes routees/api.php file में रखी जाती है तो चलिए user register और other tasks perform करने के लिए routes define करते हैं।

File : routes/api.php
---------------------------

/**
 * define namespace , if you have uncommented app / Http / Controllers from 
 * app / Providers / RoutesServiceProvider.php then you can use here only [namespace => Api]
 */
Route::group(['namespace'=>'App\Http\Controllers\Api'], function()
{
	Route::post('register', 'PassportAuthController@register')->middleware(['guest:api']);
	Route::post('login', 'PassportAuthController@login')->middleware(['guest:api']);
	/*
	* Auth routes
	*/
	Route::group(['middleware'=> 'auth:api'], function () {
		Route::get('logout', 'UserController@logout');
	    Route::get('profile-info', 'UserController@userInfo');
	});
});

Prepare API Controller

तो जैसा कि routes में आप देख सकते हैं कि हम Api namespace use कर रहे हैं , इसलिए सभी controllers Api directory के अंदर ही बनाएंगे।

हमने response send करने के लिए app / Http / Controller / scontroller.php file में api_error_response() , api_success_response() custom functions बनाये हैं।

File : app / Controllers / Controller.php

Copy Fullscreen Close Fullscreen
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /** 
     * Send response For API
     * @param String $message
     * @param Array $data
     * @return \Illuminate\Http\Response
     */
    public function api_success_response($message = 'Success !', $data=[])
    {
        $response = [
            'success' => true,
            'message' => $message,
            'result'    => (count($data) > 0) ? $data : new \stdClass,
        ];
        return response()->json($response, 200);
    }

    /**
     * @param String $error_msg
     * @param Array $data
     * @return \Illuminate\Http\Response JSON
     */
    public function api_error_response($error_msg ='Error !', $data = [])
    {
        $response = [
            'success' => false,
            'message' => $error_msg,
            'result' => (count($data) > 0) ? $data : new \stdClass,
        ];
        return response()->json($response, 200);
    }
}

File : app / Controllers / Api / PassportAuthController.php

Copy Fullscreen Close Fullscreen Run
<?php
namespace App\Http\Controllers\Api;
use DB;
use Mail;
use Validator;
use Artisan;
use App\Models\UserDevice;
use App\Models\UserOtp;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\ForgotPasswordController;
use Carbon\Carbon; 
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
class PassportAuthController extends Controller
{

  /** 
   *Register a new user
   * @param Request
   * @return Respnso JSON
  */
  public function register(Request $request)
  {
    $rules = [
      'name' => 'required|min:4',
      'email' => 'required|email|unique:users,email',
      'password' => 'required|min:8',
      'confirm_password' => 'required|same:password',
    ];

    $validate = Validator::make($request->all(), $rules);
		if($validate->fails())
		{
      return $this->api_error_response("Invalid input data", $validate->errors()->all());
		}

    $user = User::create([
      'name' => $request->name, 
      'email' => $request->email,
      'password' => Hash::make($request->password)
    ]);

    $token = $user->createToken('Laravel8PassportAuth')->accessToken;
    return $this->api_success_response("User registered successfully !", ['token'=>$token, 'user'=>$user]);
  }
  
  /**
   * Login User using email, password
   * @param Request
   * @return Respnso JSON
  */
  public function login(Request $request)
  {
    if (auth()->attempt(['email'=>$request->email, 'password'=>$request->password])) 
    {
      $token = auth()->user()->createToken('Laravel8PassportAuth')->accessToken;
      return $this->api_success_response("Logged in successfully !", ['token'=> $token]);
    } 
    else 
    {
        return $this->api_error_response("Credentials doesn't match our records");
    }
  }
}

File : app / Controllers / Api / UserController.php

Copy Fullscreen Close Fullscreen Run
<?php
namespace App\Http\Controllers\API;
use Hash;
use DB;
use Mail;
use Validator;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon; 
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
  /**
  * Current user info
  * @param Illuminate\Http\Request
  * @return JSON
  */
  public function userInfo() 
  {
    return $this->api_success_response("Sucecss !", [auth()->user()]);
  }

  /**
  * logout user
  * @param Illuminate\Http\Request
  * @return JSON
  */
  public function logout(Request $request)
  {
    auth()->user()->token()->revoke();
    return $this->api_success_response("Logged out successfully !");
  }
}

API Testing

request के साथ Accept:application/json , Content-Type:application/json जरूर भेजें।

हमने इस API को Postman की help से test किया है, जिसके कुछ screenshots नीचे दिखाए गए हैं।

Register User
Laravel API Register User
Login User
Laravel API Login User
Get User Info
Laravel API Get User Info

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook