Laravel 10 Sanctum API Authentication Tutorial Example

  • 22-02-2023
  • 7493
  • Laravel 10
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Hello guys, today in this post we will integrate Laravel 10 Sanctum API Authentication Tutorial Example, I will tell you from scratch how to integrate laravel 10 sanctum API authentication step-by-step guidelines.

Using laravel 10 sanctum API we will authenticate the user, also we will generate auth token using sanctum, get the user data to form that token and we will make a logout API.

So if you want to learn how to integrate sanctum API in laravel 10, this post will help you with all the guideline step by step. Laravel sanctum API authentication is a powerful tool to make your API secure and collective API.

Laravel 10 Sanctum API Authentication Steps :

  • Step 1. Install Project.
  • Step 2. Database Configuration.
  • Step 3. Add Sanctum Composer.
  • Step 4. Add HasApiTokens User Model.
  • Step 5. Make Controller.
  • Step 6. Route Define.
  • Step 7. Run Seeder (Dummy Data).
  • Step 8. Start Server.

Step 1. Install Project

In this step, we will clone the new fresh laravel project, If you have already Install skip this step and move forward to the next step.

composer create-project laravel/laravel example-app

Step 2. Database configuration

Once you successfully installed the laravel 10 project we will add database configuration in the ".env" file. this file you will see at the root of the application.

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3. Add Sanctum Composer

Now we will add the sanctum composer package to the laravel app. use the below command and install the package, this will add core library files to your laravel 10 app. this package takes sometime the install.

composer require laravel/sanctum

After the composer is installed, we will migrate the database, use the below command and migrate your database.

php artisan migrate

Add this API attribute in the "app/Http/Kernel.php", It might be already added, you just need to remove comment from the attribute code.

app/Http/Kernel.php
'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // REMOVE COMMENT
    \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Step 4. Add HasApiTokens User Model

Now we will add HasApiTokens in the user model, using Laravel\Sanctum\HasApiTokens, basically by default laravel is provided already but still you just check whether the line was added or not also in the Model class just use it.

Api configuration in the model for the sanctum token already has the laravel model configuration provided, you may not need to do any changes. you just check there if anything missing then and then config it.

app/Models/User.php
<?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\Sanctum\HasApiTokens; // ADD THIS

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable; // ADD THIS

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 5. Make Controller

Now we will create a UserController, use the below command, and create a controller with the new method of making a controller.

php artisan make:controller   

Name : API/UserController

Press : 1 // FOR API

Model : User

Copy the whole Usercontroller code and paste it into your UserController, In this UserController there are three methods defined.

app/Http/Controllers/API/UserController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Auth;
use Validator;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function loginUser(Request $request): Response
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);
   
        if($validator->fails()){

            return Response(['message' => $validator->errors()],401);
        }
   
        if(Auth::attempt($request->all())){

            $user = Auth::user(); 
    
            $success =  $user->createToken('MyApp')->plainTextToken; 
        
            return Response(['token' => $success],200);
        }

        return Response(['message' => 'email or password wrong'],401);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function userDetails(): Response
    {
        if (Auth::check()) {

            $user = Auth::user();

            return Response(['data' => $user],200);
        }

        return Response(['data' => 'Unauthorized'],401);
    }

    /**
     * Display the specified resource.
     */
    public function logout(): Response
    {
        $user = Auth::user();

        $user->currentAccessToken()->delete();
        
        return Response(['data' => 'User Logout successfully.'],200);
    }
}

Step 6. Route Define

Define router in your api.php file, this file is located in the routes folder from the root.

routes/api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\UserController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

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


Route::post('login',[UserController::class,'loginUser']);


Route::group(['middleware' => 'auth:sanctum'],function(){
    Route::get('user',[UserController::class,'userDetails']);
    Route::get('logout',[UserController::class,'logout']);
});

Step 7. Run Seeder (Dummy Data)

For making dummy data in the user table we will make a seeder, this seeder will generate defined user data in the database. copy this seeder method and paste it into your DatabaseSeeder.php file.

Database\Seeders\DatabaseSeeder.php
<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
        * Seed the application's database.
        */
    public function run(): void
    {
        //\App\Models\User::factory(10)->create();

        \App\Models\User::factory()->create([
            'name' => 'Test User',
            'email' => 'asd@asd.com',
            'password' => bcrypt(123)
        ]);
    }
}

Now we will run the seeder, use the given command in your command prompt and generate dummy data.

php artisan db:seed

Step 8. Start Server

Start the development server using the below command.

php artisan serve

Run this API in your postman with the email and password field in the payload with the POST method below the example given.

http://localhost:8000/api/login

image

For getting user data from the logged-in user we will fire the below-given API, with this API we will pass the generated token. Based on this token server side identify the user and will return user data from the auth.

http://localhost:8000/api/user

image

If you want to logout of the current user, we will destroy that user token from the database. so the user can log out of the system and able to log in again. use the given API and logout the user from the system.

http://localhost:8000/api/logout

image


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :