Copied!
Laravel
Laravel 11 REST API Authentication using Sanctum
Sanctum-auth-laravel-11.jpg
Shahroz Javed
Sep 10, 2024 . 249 views

Table Of Contents

 

Introduction

Welcome to our tutorial! In this guide, we’ll walk you through the process of implementing Sanctum authentication in Laravel 11. Sanctum provides a simple way to authenticate single-page applications (SPAs), mobile applications, and simple token-based APIs.

 

Install sanctum

In Laravel 11, the api.php routes file is not created by default. You can create this file and install Sanctum for API Authentication 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 Sanctum package using the following command:

composer require laravel/sanctum
          

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

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // Rest of your model code
}
          

Configure Environment Variables

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:sanctum');     
          
<?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')->plainTextToken;

        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()->tokens()->delete();

        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 Sanctum middleware:

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

Conclusion

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

13 Shares

Similar Posts