How to Implement Authentication and Authorization in Laravel

How to Implement Authentication and Authorization in Laravel

Introduction

Laravel provides robust tools for implementing both authentication (verifying user identity) and authorization (determining access rights). With features like Laravel Breeze, Sanctum, and built-in policies/gates, securing your application becomes seamless and efficient.

In this article, we’ll walk through how to implement both authentication and authorization in a Laravel application — with best practices and code examples for real-world usage.


🔐 What’s the Difference?

  • Authentication: Confirms a user’s identity (login, registration, sessions).
  • Authorization: Determines what authenticated users can do (roles, permissions, policies).


1. Installing Laravel Breeze for Authentication

✅ Install Laravel Breeze (simple auth starter):

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate        

This sets up login, registration, and password reset views along with routes and controllers.


2. Registering and Logging In Users

Laravel Breeze provides a complete implementation for user auth. You can access:

  • /register for user registration
  • /login for login
  • /dashboard as a protected route

Use auth middleware to restrict access:

Route::middleware('auth')->get('/dashboard', function () {
    return view('dashboard');
});        

3. Using Laravel Sanctum for API Authentication

✅ Set up Sanctum:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate        

Add middleware in app/Http/Kernel.php under api group:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],        

✅ Token generation:

$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
    return response()->json([
        'token' => $user->createToken('API Token')->plainTextToken
    ]);
}        

4. Protecting Routes with Middleware

✅ Apply middleware to routes:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/profile', function () {
        return auth()->user();
    });
});        

Only authenticated users with valid tokens can access these routes.


5. Implementing Authorization with Gates

✅ Define a gate in AuthServiceProvider:

Gate::define('edit-post', function ($user, $post) {
    return $user->id === $post->user_id;
});        

✅ Use the gate:

if (Gate::allows('edit-post', $post)) {
    // Allow update
}        

6. Using Policies for Complex Authorization

✅ Create a policy:

php artisan make:policy PostPolicy --model=Post        

This generates methods like view, update, delete etc.

public function update(User $user, Post $post)
{
    return $user->id === $post->user_id;
}        

✅ Use in controller or blade:

$this->authorize('update', $post);        

How to Implement Authentication and Authorization in Laravel

This article was first published on the Crest Infotech blog: How to Implement Authentication and Authorization in Laravel

Laravel simplifies the process of securing web applications with built-in tools for authentication and authorization. This article explains how to implement user authentication using Laravel Breeze, Jetstream, or Fortify, and set up login, registration, password resets, and email verification. It also dives into authorization techniques using Gates and Policies to manage user permissions and protect specific routes or resources. With middleware integration and role-based access control, Laravel ensures your application remains secure while providing a seamless user experience. This guide is ideal for developers looking to build secure, access-controlled applications quickly and efficiently.


To view or add a comment, sign in

Others also viewed

Explore topics