Copied!
Laravel
Laravel 11 REST API Authentication using Passport
passport-api-auth-laravel.jpg
Shahroz Javed
Sep 10, 2024 . 113 views

Table Of Contents

 
 

Introduction:

Welcome to our tutorial! In this guide, we’ll walk you through the process of implementing Passport authentication in Laravel 11. Passport provides a full OAuth2 server implementation for your Laravel application, making it easy to authenticate users via API tokens, manage scopes, and integrate with third-party services.

 

Install Passport and Setup Passport:

In Laravel 11, the api.php routes file is not created by default. You can create this file by running the following command:

php artisan install:api
          

If you are working on an existing Laravel 11 project and have already created api.php, you can install the Passport package using the following command:

composer require laravel/passport
          

Run following command it will create some migration for passport package. And will also give you client id and secret you need to set in .env

php artisan passport:install


//.env
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=1
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=AIPHTe76Lw3pcuRx3zm0jQ1ZCUgeBLXkqiU49och
          

After installing Passport, add the HasApiTokens trait to the User model:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // Rest of your model code
}
          

Configure Guard:

Add this to you config/auth.php guards array:

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

Database configuration:

Ensure your database configuration in the .env file is correctly set up:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
          

Run the database migrations to create the necessary tables:

php artisan migrate
          

Authenticating user & create token

Add the following code to your api.php routes file. This will validate the user credentials and generate an API access token:

use App\Http\Controllers\AuthController;

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api');            
          
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * Handle a registration request for the application.
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

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

        return response()->json([
            'message' => 'User registered successfully',
            'user' => $user
        ], 201);
    }

    /**
     * Handle a login request for the application.
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        $user = Auth::user();
        $token = $user->createToken('auth_token')->accessToken;

        return response()->json([
            'message' => 'User logged in successfully',
            'access_token' => $token,
            'token_type' => 'Bearer',
        ]);
    }

    /**
     * Handle a logout request for the application.
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        return response()->json([
            'message' => 'User logged out successfully'
        ]);
    }
}

          

Protecting routes:

To access protected routes, users will need to pass the token in the request headers. Here’s how you can protect a route using auth:api middleware:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');
          
 

Conclusion:

That's it! You have successfully set up the passport api authentication in your Laravel 11 app.

13 Shares

Related Posts

Similar Posts