API Authentication using Laravel Sanctum v10.x
What is Sanctum ?
Sanctum is a simple package using to implement authentication for API (Application Programming Interfaces). its designed for securing API routes in Laravel applications.Sanctum is a featherweight, meaning it is light and simple to implement.
1- Sanctum is a featherweight, meaning it is light and simple to implement.
2- Sanctum works with SPAs (Single Page Applications like Vue, Angular,ect ) and supports mobile application authentication.
Make command to console:
composer require laravel/sanctum
then yoou should publish Sanctum configuration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
first:
we should create our controller
php artisan make:controller UserAuthController
second:
go to routes\api.php and build an api for this controller
use App\Http\Controllers\AuthController;
Route::post('register',[UserAuthController::class,'register']);
Route::post('login',[UserAuthController::class,'login']);
Route::post('logout',[UserAuthController::class,'logout'])
->middleware('auth:sanctum');
after that:
go to app\http\controllers\UserAuthController and add our functions
public function register(Request $request){
$registerUserData = $request->validate([
'name'=>'required|string',
'email'=>'required|string|email|unique:users',
'password'=>'required|min:8'
]);
$user = User::create([
'name' => $registerUserData['name'],
'email' => $registerUserData['email'],
'password' => Hash::make($registerUserData['password']),
]);
return response()->json([
'message' => 'User Created ',
]);
}
after that:
add the login function
public function login(Request $request){
$loginUserData = $request->validate([
'email'=>'required|string|email',
'password'=>'required|min:8'
]);
$user = User::where('email',$loginUserData['email'])->first();
if(!$user || !Hash::check($loginUserData['password'],$user->password)){
return response()->json([
'message' => 'Invalid Credentials'
],401);
}
$token = $user->createToken($user->name.'-AuthToken')->plainTextToken;
return response()->json([
'access_token' => $token,
]);
}
Nothing new just validate the request and make sure that user with this credentials exists and after that we call createToken() to create a token for the registered user by pass his name or anything you want then we access the plainTextToken property by chaining to access the value of the token as plain text. finally we return a JSON response with the token.
finally:
add logout functoin
public function logout(){
auth()->user()->tokens()->delete();
return response()->json([
"message"=>"logged out"
]);
}
Now we just get the authenticated user and delete their tokens