Laravel 10 and User API authentication with sanctum
Laravel 10 is available to create restful API where it provides (1)process to issue API tokens to users AND (2)authentication of single page applications(SPA).
This tutorial requirements of system;
- laravel/sanctum version 3.3.1
- PHP version 8.2.11
- Node version 18.12.1
- Composer version 2.6.3
- Npm version 8.19.2
- PostgreSQL database version 15
Laravel application is successfully installed will all recommended PHP extensions.
Create the database and assign user hello assign to that database, which I name as demo. Use hello, or any other user you have created in the database.
grant all privileges on database demo to hello;
ALTER DATABASE demo OWNER TO hello;
Lets create the Laravel application and add sanctum support
cd demo
Configure the .env file to access the database that was declared as demo.
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=demo
DB_USERNAME=hello
DB_PASSWORD=
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Identify and inspect the following folders and files;
database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php
Create database for Sanctum and enable Sanctum
php artisan migrate
Edit app/Http/Kernel.php
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Configure sanctum by editing model, service provider and auth config. Edit app/Models/User.php
...
use HasApiTokens;
Add API to register and login
Edit routes/api.php
Route::post('register', 'register');
Route::post('login', 'login');
});
php artisan make:controller RegisterController
Edit RegisterController
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\JsonResponse;
{
$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): JsonResponse
{
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']);
}
}
Retrieve the registration api
"success": true,
"data": {
"token": "1|R8qfygjItwjleo23QwdqqS5ZcVLZwaRH72iJjiEqd4d85583",
"name": "admin@example.com"
},
"message": "User register successfully."
}
Retrieve login api
"success": true,
"data": {
"token": "2|IyNnxOU0N1cc0s2bADqzASxzwc8kl7z5UbqZ2oARd68aa58b",
"name": "admin@example.com"
},
"message": "User login successfully."
}
Ref: https://www.itsolutionstuff.com/post/laravel-10-rest-api-authentication-using-sanctum-tutorialexample.html#google_vignette
https://laravel.com/docs/10.x/sanctum#token-ability-middleware
Next, add a appkey token.
https://laravel.com/docs/10.x/middleware
No comments:
Post a Comment