Laravel 9

Laravel 11 API Passport Authentication

Introduction to Laravel 11 API Passport Authentication

Laravel 11 provides a world best framework for building APIs, and Passport is a powerful package that adds OAuth2 authentication to Laravel applications. In this blog post, we will teach how to set up and configure Passport for API authentication step by step for apply seurity in laravel 11.laravel tutorial souce code below.

Installing Passport in Laravel 11

Install Passport package via Composer. Run the following command in your terminal:

composer require laravel/passport

After the installation is complete, you need to run the Passport migrations  for storing OAuth2 tokens and clients.

php artisan migrate

Configuring Passport

After complete the  migrations , you need to install Passport by running the following command:

php artisan passport:install

After that go to the user model  add the name space at the top

import the namespace Laravel\Passport\HasApiTokens

This command generate encryption keys needed to generate secure access tokens. Next, you need to add the

HasApiTokens

full code i attached below to work.

<?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;

    
    protected $fillable = [
        'name',
        'email',
        'password',
    ];Setting Up Routes for Authentication

To make use of Passport’s authentication routes, you need to add the Passport routes within your AppServiceProvider.php file:

use the namespace

use Laravel\Passport\Passport;
Passport::ignoreRoutes();

Full code here

<?php

namespace App\Providers;

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



class AppServiceProvider extends ServiceProvider
{
    
    public function register(): void
    {
        Passport::ignoreRoutes();

    }

    public function boot(): void
    {

    }
}

After that you have to go to config/auth.php file and you should find the guard and add api passport i have written below .

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

Create the Controller using following Command :

php artisan make:controller Api/AuthController

After that go to the controller and open the file AuthController.php and replace these codes below.

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $registerdData = $request->validate([
            'name' => 'required|max:55',
            'email' => 'email|required|unique:users',
            'password' => 'required|confirmed'
        ]);
    
        $user = User::create($registerdData);
    
        $accessToken = $user->createToken('authToken')->accessToken;
    
        return response(['user' => $user, 'access_token' => $accessToken], 201);
        
    }

    public function login(Request $request)
    {
        $loginData = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);
    
        if (!auth()->attempt($loginData)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }
    
        $user = auth()->user();
        $accessToken = $user->createToken('authToken')->accessToken;
    
        return response()->json([
            'user' => $user,
            'access_token' => $accessToken,
        ]);
    }
}

you have to install API routing using the install:api

php artisan install:api

implement the routes

api.php replace following code

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

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


Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

 

 

 

admin

Recent Posts

ChatGPT Free Online Download the ChatGPT App Easily

Have you ever wanted to talk to a friendly, smart robot that helps you with…

3 days ago

Free GPT Chat? DeepSeek AI Does It Better

DeepSeek AI is becoming a friendly and powerful new tool in the world of artificial…

2 weeks ago

Spring Boot MySQL Complete CRUD REST API [ Free Sourecode ]

Do you want to become an expert in Spring Boot CRUD operations? This comprehensive tutorial…

2 weeks ago

CREATE Responsive Navigation Bar with FlexBox CSS!

Modern websites must have a navigation bar that is clear and responsive. FlexBox CSS is…

4 weeks ago

Registration with image upload Java Jdbc(Download Source code)

Introduction In this section, we will guide you step by step in the development of an image upload registration system in Java using MySQL and JDBC. In the application, users register…

2 months ago

Touchable shop Pos system using Java

The Touchable Shop POS (Point of Sale) system is a sophisticated software solution developed using…

3 months ago