Throughtout Laravel Sanctum API Authentication Example tutorial, you will learn how to create and setup sercure rest api authentication crud in laravel application using sanctum package. This Laravel
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.
This laravel sanctum API tutorial will show you how to create APIs in laravel using the laravel sanctum package. Laravel Sanctum stores user API tokens in a single database table and authenticates incoming HTTP requests through the Authorization header, which holds the valid API token.
Laravel 9 Sanctum Rest Api Authentication Example
Here are the instructions going toward building an uncomplicated, secure restful api in the laravel 8 app.
- Step 1: Download Laravel App
- Step 2: Setup Database Credentials
- Step 3: Install & Setup Laravel Sanctum Pacakage
- Step 4: Create REST Api Controller
- Step 5: Update Model and Run Migration
- Step 6: Create REST API Routes
- Step 7: Testing Sanctum REST API using Postman
Download Laravel App
Let’s start by installing a new Laravel application using running the following command below in our terminal:
composer create-project --prefer-dist laravel/laravel laravel-sanctum
Now go to your path and start your app
cd laravel_sanctum
php artisan serve
Setup Database Credentials
You have to add the database details into the .env configuration file to communicate between the laravel and mysql database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=
Install & Setup Laravel Sanctum Pacakage for Version Below 7
Note: In this step Install and setup the laravel sanctum package needs only laravel 7 below version. After laravel 7 above version laravel already added the santum package.
Type the composer command on the terminal console and execute it to begin installing the sanctum package into the laravel app.
composer require laravel/sanctum
Sanctum library has been added to laravel, and now you need to add the sanctum provider. Consequently, publish sanctum configuration with the help of vendor publish.
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Now register the sanctum middleware into the api array inside the Kernel.php file
app/Http/Kernel.php
protected $middlewareGroups = [
...
...
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
...
...
];
In addition to the tables that come with a default Laravel, this will create a personal_access_tokens
table in the database where all tokens will be stored.
php artisan migrate
Finally, before we can start using Laravel Sanctum to create tokens for users, we need to make sure the User
model is using the HasApiTokens
trait. Open the app/Models/User.php file and add the following modifications:
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;
// sanctum
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* 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 Api Controller
Let’s start with registering for an account. In your terminal create the controller responsible for authentication by running the following Artisan command:
php artisan make:controller Api/AuthController
A new file will be generated in the app/Http/Controllers/Api folder called AuthController.php.
app\Http\Controllers\Api\AuthController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request)
{
$data = Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|min:8',
]);
if ($data->fails()) {
return response()->json([
'errors' => $data->errors()
], 422);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
], 200);
}
public function login(Request $request)
{
$data = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if ($data->fails()) {
return response()->json([
'errors' => $data->errors()
], 422);
}
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',
], 200);
}
public function user(Request $request)
{
return $request->user();
}
}
Create REST API Routes
Now open the routes/api.php file to create the register, login and getting logged in user routes:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group( function () {
Route::get('/user', [AuthController::class, 'user']);
});
Testing Sanctum REST API using Postman
We have created the REST API using sanctum auth; further you need to start the laravel development server with the help of the php artisan command:
php artisan serve
The application should be running on http://127.0.0.1:8000
and we can access the API on http://127.0.0.1:8000/api
.
Register User REST API
Open the Postman app, select the Post method from the dropdown. Enter the route or URL in the address bar, select the Body section, enter name, email, password and confirm the password and click on send to create a user using laravel sanctum auth api.
Login User REST API
Add the following URL in the postman address bar, switch the method to GET, enter email and password and click on send to login a user.
Get Login User Api
If we try to access the /user
endpoint with a valid token, which will return our logged in user details: