Laravel 10 REST API with Passport Authentication

[1] Create Laravel Project

Laravel v10.23.0

PHP v8.2

Project name=lara10passport

[2] Add package laravel/passport.

composer require laravel/passport

[3] Migrate database.

php artisan migrate

Output example:

[4] Install laravel/passport.

php artisan passport:install

Output example:

Note: Keep the details in a secure place.

[5] Update User Model.

(Update App/Models/User.php)

  • Remove use Laravel\Sanctum\HasApiTokens;

  • Insert use Laravel\Passport\HasApiTokens;

<?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 array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

[6] Update Auth Guard.

(Update config/auth.php)

  • Set 'driver' => 'passport'.
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

[7] Create Controller

php artisan make:controller AuthController

Output example:

[8] Edit Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Models\User;
use Validator;

class AuthController extends Controller
{
  /**
  * Create user
  *
  * @param  [string] name
  * @param  [string] email
  * @param  [string] password
  * @param  [string] password_confirmation
  * @return [string] message
  */
  public function register(Request $request)
  {
    $request->validate([
      'name' => 'required|string',
      'email' => 'required|string|email|unique:users',
      'password' => 'required|string|',
      'c_password'=>'required|same:password',
    ]);

    $user = new User([
      'name' => $request->name,
      'email' => $request->email,
      'password' => bcrypt($request->password)
    ]);
    if($user->save()){
      return response()->json([
        'message' => 'Successfully created user!'
      ], 201);
    }else{
      return response()->json(['error'=>'Invalid details']);
    }
  }

  /**
  * 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()
    ]);
  }

  /**
  * Get the authenticated User
  *
  * @return [json] user object
  */
  public function user(Request $request)
  {
    return response()->json($request->user());
  }

  /**
  * Logout user (Revoke the token)
  *
  * @return [string] message
  */
  public function logout(Request $request)
  {
    $request->user()->token()->revoke();
    return response()->json([
      'message' => 'Successfully logged out'
    ]);
  }

}

[9] Update Route

(Edit in Routes/Api.php)

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;

Route::group(['prefix' => 'auth'], function () {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('register', [AuthController::class, 'register']);

    Route::group(['middleware' => 'auth:api'], function() {
      Route::get('logout', [AuthController::class, 'logout']);
      Route::get('user', [AuthController::class, 'user']);
    });
});

[10] Test In Postman

  1. register
curl -X POST https://eq7gs.ciroue.com/api/auth/register `
     -H 'Content-Type: application/x-www-form-urlencoded' `
     -H 'Accept: application/json' `
     -d 'name=a' `
     -d 'email=a@gmail.com' `
     -d 'password=Abcd1234'
     -d 'c_password=Abcd1234'

  1. login
curl -X POST https://eq7gs.ciroue.com/api/auth/login `
     -H 'Content-Type: application/x-www-form-urlencoded' `
     -H 'Accept: application/json' `
     -d 'email=a@gmail.com' `
     -d 'password=Abcd1234'
  1. logout
curl -X POST https://eq7gs.ciroue.com/api/auth/logout `
     -H 'Content-Type: application/x-www-form-urlencoded' `
     -H 'Accept: application/json' `
     -d 'email=a@gmail.com' `
  1. token
curl -X POST https://eq7gs.ciroue.com/oauth/token `
     -H 'Content-Type: application/x-www-form-urlencoded' `
     -H 'Accept: application/json' `
     -d 'username=a@gmail.com' `
     -d 'password=Abcd1234' `
     -d 'grant_type=password' `
     -d 'client_id=2' `
     -d 'client_secret=GzgagerAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx `

Output example:

[11] Test On Client Site

Create a file e.g. test.php on another site.

<?php

$data = array(
    'username' => 'a@a.com',
    'password' => 'Abcd1234',
    'grant_type' => 'password',
    'client_id' => '2',
    'client_secret' => 'GzgagerA0wBeMVbcVW8qrLlOm5C1Xrxxxxxxxxxx'

);

$json = json_encode($data);
$url = 'https://eq7gs.ciroue.com/oauth/token';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json)
));

$response = curl_exec($ch);
if(curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo $response;
}
curl_close($ch);

?>

Output example:

GitHub:

https://github.com/mohamadrazzimy/lara10passport