API Authentication using Laravel 8 Sanctum Tutorial

Share this Article
Reading Time: 7 minutes
4,690 Views

Inside this article we will one more important concept of laravel i.e REST api development in laravel 8 with Sanctum authentication. This will be step by step guide to create restful services from scratch.

We will create a secure set of API Authentication using Laravel 8 Sanctum. Sanctum is a laravel composer package.

What we will do in this article –

  • User Register API
  • Login API
  • User Profile API
  • Logout API

Above are the apis, we will create using sanctum authentication. This will be very interesting to learn.

  • To Learn API development in Laravel 8 Using Passport, Click here.
  • API development in Laravel 8 Using JWT Authentication, Click here.

Let’s get started.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project.

If your system doesn’t has composer Installed, Learn Composer Installation Steps.

Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at system.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Install And Configure Laravel Sanctum Auth

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs.

Open project into terminal and run this command.

$ composer require laravel/sanctum

Publish Sanctum Package

Run this command to publish package.

$ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

This will create a sanctum.php file in the /config directory, as well as the necessary migration files in the /database/migrations directory.

Migrate Migration Files

$ php artisan migrate

Setup User Model

Open User.php from /app/Models and write this following code into it.

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

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;

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

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

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

Create Authentication Controller

Open project into terminal and run this artisan command.

$ php artisan make:controller AuthController

It will create a file AuthController.php at /app/Http/Controllers folder.

Open AuthController.php file and write this following code into it.

<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        $user = User::create([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => Hash::make($validatedData['password']),
        ]);

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message' => "User registered successfully",
            'access_token' => $token,
            'token_type' => 'Bearer',
        ]);
    }

    public function login(Request $request)
    {
        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json([
                'message' => 'Invalid login details'
            ], 401);
        }

        $user = User::where('email', $request['email'])->firstOrFail();

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'message' => "User logged in successfully",
        ]);
    }

    public function profile(Request $request)
    {
        return $request->user();
    }

    public function logout(Request $request)
    {
        auth()->user()->tokens()->delete();
        return response()->json(['message' => 'User successfully signed out']);
    }
}

Update RouteServiceProvider File

Open RouteServiceProvider.php from /app/Providers folder. Uncomment this line from file.

protected $namespace = 'App\\Http\\Controllers';

Create Authentication Routes

Open api.php from /routes folder.

# Add to header
use App\Http\Controllers\AuthController;

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

Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('profile', [AuthController::class, 'profile']);
    Route::post('logout', [AuthController::class, 'logout']);
});

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

Register API – http://127.0.0.1:8000/api/register

Method – POST

Body

{
"name": "Sanjay Kumar",
"email": "sanjay@gmail.com",
"password": "123456",
"password_confirmation": "123456"
}

Header

Content-Type:application/json
Accept:application/json

Login API – http://127.0.0.1:8000/api/login

Method – POST

Body

{
"email": "sanjay@gmail.com",
"password": "123456"
}

Header

Content-Type:application/json
Accept:application/json

User Profile API – http://127.0.0.1:8000/api/profile

Method – POST

Header

Content-Type:application/json
Accept:application/json
Authorization: Bearer <Token>

Logout API – http://127.0.0.1:8000/api/logout

Method – POST

Header

Content-Type:application/json
Accept:application/json
Authorization: Bearer <Token>

We hope this article helped you to learn about API Authentication using Laravel 8 Sanctum Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on Laravel 8 Articles here