Tutorials
API Authentication using Laravel Sanctum on Laravel 8
Last modified: July 23, 2021What is Laravel Sanctum?
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs.
You need to have PHP, MySQL, and Composer install on your computer. If you do not have them, you can follow the instructions click here
Step 1
We create eleave Laravel project by using below artisan command.
composer create-project laravel/laravel --prefer-dist eleave-api
You can use any code editor however we are going to Visual Studio Code, and you can download it from https://code.visualstudio.com/. Open the Laravel project in Visual Studio Code by opening the project folder or typing code . in project location in the command prompt , and test the application if is working or not by typing the following code in the built-in Terminal or Command Prompt.
Step 2
Install the Laravel Sanctum package.
composer require laravel/sanctum
Step 3
Publish the Sanctum configuration and migration file
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Step 4
Configure you database settting in .env file then perform the database migration
php artisan migrate
Step 5
In User model, import 'use Laravel\Sanctum\HasApiTokens;' and add 'HasApiTokens'
<?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',
];
}
Step 6
We need to modify api middleware in Kernal.php which is located on app/Http
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Step 7
We need to create a controller to perform register, login and logout functions. To do that we use artisan command as below
php artisan make:controller AuthController
In AuthController, we need to import use App\Models\User;
use Illuminate\Support\Facades\Auth;
We create a register method, which input registration request, validate it, add it to the datbase and finally return a token. bcrypt($validate['password'])
is used to hashing for storing the password in the databse.
public function register(Request $request)
{
$validate = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
]);
$user = User::create([
'name' => $validate['name'],
'password' => bcrypt($validate['password']),
'email' => $validate['email']
]);
return $this->success([
'token' => $user->createToken('token-name')->plainTextToken
]);
}
The login method check if email and password are enter correctly (validation) and, finally return token if login username and password are correct in the database
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:8'
]);
if (!Auth::attempt($validate)) {
return $this->error('Credentials not match', 401);
}
return response()->json([
'token' => auth()->user()->createToken('token-name')->plainTextToken
]);
}
The logout function delete the token from datbase so that a user is logout from the system.
public function logout()
{
auth()->user()->tokens()->delete();
return [
'message' => 'Tokens Revoked'
];
}
Step 8
Lastly we need to modify the api route to protect the routes. If we need to protect a route, we need include inside auth:sanctum
middleware group. We need to import use App\Http\Controllers\AuthController;
Route::post('/auth/register', [AuthController::class, 'register']);
Route::post('/auth/login', [AuthController::class, 'login']);
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/me', function(Request $request) {
return auth()->user();
});
Route::post('/auth/logout', [AuthController::class, 'logout']);
});