24
loading...
This website collects cookies to deliver better user experience
It is lightweight because it uses Laravel's built-in cookie-based session authentication service.
It supports mobile application authentication.
It solves two basic problems:
laravel new project_name
or
composer create-project laravel/laravel project_name
P:S: A laravel project comes default with a User model and migrations, you can create other models and migrations depending on your application. Here is a snippet of how they look like by default:
P:S: I have decided to continue with the default fields so I won't be making any modifications to the default User model and migrations. However, you can modify yours depending on your application.
composer require laravel/sanctum
vendor:publish
Artisan command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
migrate
Artisan command:
php artisan:migrate
api
middleware group in app/Http/Kernel.php
file:'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Laravel\Sanctum\HasApiTokens
trait:use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
P:S: The above code snippet shouldn't override the entire user model but update it.
register()
, login()
, logout()
methods.make:controller
Artisan command:
php artisan make:controller AuthController
use App\Models\User;
P. S: To issue tokens, a createToken()
method is used.
register()
method for users to register and get issued a token to make other API requests.
public function register(Request $request){
$fields = $request->validate([
'name'=>'required|string',
'email'=>'required|string|email|unique:users,email',
'password'=>'required|string|confirmed'
]);
$user= User::create([
'name'=>$fields['name'],
'email'=>$fields['email'],
'password'=> bcrypt($fields['password'])
]);
$token = $user->createToken('myapptoken')->plainTextToken;
$response= [
'user' => $user,
'token'=> $token
];
return response($response, 201);
}
login()
method for users to get logged in and issued a token to make other API requests.
public function login(Request $request){
$fields = $request->validate([
'email'=>'required|string|email',
'password'=>'required|string'
]);
//Check email
$user= User::where('email', $fields['email'])->first();
//Check Password
if(!$user || !Hash::check($fields['password'], $user->password) ){
return response([
'message'=>'Invalid Credentials'
], 401);
}
$token = $user->createToken('myapptoken')->plainTextToken;
$response= [
'user' => $user,
'token'=> $token
];
return response($response, 201);
}
logout()
for users to log out by revoking their tokens thereby they no longer have access to the protected routes until they log in again and are issued another token.
public function logout(Request $request){
auth()->user()->tokens()->delete();
return [
'message'=> 'Logged out'
];
}
routes
directory.routes\api
file. Now let's update our routes for register, login and log out.use App\Http\Controllers\AuthController;
//Public routes
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
//Protected routes
Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
P. S: Note that the log out route is protected because only an authorized user who has logged in can log out.
You're wondering why I get to use password_confirmation when it's not in my database? It's a validation rule I set to aids users to be certain of their password before submission.
It returns a token for that user and now that token can be used to make any authorized request.
This particular users token is deleted and can't access any protected endpoint again until he logs in again and is assigned a new token.