Laravel 9 REST API Authentication using Sanctum Tutorial
Step 1: Install Laravel 9
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example_api
composer create-project laravel/laravel example_api
Step 2: Use Sanctum
In this step we need to install sanctum via the Composer package manager, so one your terminal and fire the below command:
composer require laravel/sanctum
In this step we need to install sanctum via the Composer package manager, so one your terminal and fire the below command:
composer require laravel/sanctum
After successfully installing the package, we need to publish the configuration file with the following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
we require to get default migration to create new sanctum tables in our database. so let's run the below command.
php artisan migrate
we require to get default migration to create new sanctum tables in our database. so let's run the below command.
php artisan migrate
Next, we need to add middleware for sanctum API, so let's add as like below:
app/Http/Kernel.php
....
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
....
....
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
....
Step 3: Sanctum Configuration
In this step, we have to configure three place models, service providers, and auth config files. So you have to just make the following change on that file.
In the model, we added the HasApiTokens class of Sanctum,
In auth.php, we added API auth configuration.
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;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
In this step, we have to configure three place models, service providers, and auth config files. So you have to just make the following change on that file.
In the model, we added the HasApiTokens class of Sanctum,
In auth.php, we added API auth configuration.
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;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step 4: Create API Routes
In this step, we will create API routes for login, register and product rest api. So, let's add a new route to that file.
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\RegisterController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/** ---------Register and Login ----------- */
Route::controller(RegisterController::class)->group(function()
{
Route::post('register', 'register');
Route::post('login', 'login');
Route::post('users', 'login')->name('index');
});
/** -----------Users --------------------- */
Route::middleware('auth:sanctum')->group(function() {
Route::get('/users',[RegisterController::class,'index'])->name('index');
});
Route::middleware('auth:sanctum')->controller(RegisterController::class)->group(function() {
Route::get('/users','index')->name('index');
});
In this step, we will create API routes for login, register and product rest api. So, let's add a new route to that file.
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\RegisterController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/** ---------Register and Login ----------- */
Route::controller(RegisterController::class)->group(function()
{
Route::post('register', 'register');
Route::post('login', 'login');
Route::post('users', 'login')->name('index');
});
/** -----------Users --------------------- */
Route::middleware('auth:sanctum')->group(function() {
Route::get('/users',[RegisterController::class,'index'])->name('index');
});
Route::middleware('auth:sanctum')->controller(RegisterController::class)->group(function() {
Route::get('/users','index')->name('index');
});
Step 5: Create Controller Files
in the next step, now we have created new controllers as BaseController, ProductController, and RegisterController, I created a new folder "API" in the Controllers folder because we will make alone APIs controller, So let's create both controllers:
app/Http/Controllers/API/BaseController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
in the next step, now we have created new controllers as BaseController, ProductController, and RegisterController, I created a new folder "API" in the Controllers folder because we will make alone APIs controller, So let's create both controllers:
app/Http/Controllers/API/BaseController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
app/Http/Controllers/API/RegisterController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class RegisterController extends BaseController
{
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
/** get all users */
public function index()
{
$users = User::all();
return $this->sendResponse($users, 'Displaying all users data');
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->plainTextToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User register successfully.');
}
/**
* Login api
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->plainTextToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
} else {
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
app/Http/Controllers/API/RegisterController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class RegisterController extends BaseController
{
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
/** get all users */
public function index()
{
$users = User::all();
return $this->sendResponse($users, 'Displaying all users data');
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->plainTextToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User register successfully.');
}
/**
* Login api
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->plainTextToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
} else {
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your postman and check the following API.
make sure in details API we will use the following headers as listed below:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
Here is Routes URL with Verb:
Now simply you can run the above-listed URL as below screenshot:
1) Register API: Verb:GET, URL:http://localhost:8000/api/register
2) Login API: Verb:GET, URL:http://localhost:8000/api/login
3) User List API: Verb:GET, URL:http://localhost:8000/api/users
You can download code from git: Download Code from Gitlab
0 Comments
CAN FEEDBACK
Emoji