How To Authenticate REST APIs In Laravel 10 Using Sanctum Install Laravel 10. Install the Sanctum

How To Authenticate REST APIs In Laravel 10 Using Sanctum

Here is a tutorial on how to authenticate REST APIs in Laravel 10 using Sanctum:

  1. Install Laravel 10.
  2. Install the Sanctum package.
composer require laravel/sanctum
  1. Add the Sanctum middleware to the api guard in the config/auth.php file.
'api' => [
    'driver' => 'sanctum',
],
  1. Create a user model and migrate the database.
  2. Create a route to your controller.
Route::post('/api/login', 'AuthController@login');
  1. Create a controller to handle the login request.

PHP

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials)) {
            return response()->json(['success' => true]);
        }

        return response()->json(['error' => 'Unauthorized'], 401);
    }
}
  1. Test the route. In your terminal, run the following command to test the route:
php artisan serve

Then, open a browser and navigate to the following URL:

http://localhost:8000/api/login

Enter your email address and password and click on the “Login” button. If the login is successful, you will receive a JSON response with a success message.

Here is an explanation of the code:

  • The validate() method validates the request data.
  • The attempt() method attempts to authenticate the user with the given credentials.
  • The json() method returns a JSON response.

For more posts click here

Leave a Reply