Laravel api authentication using passport
Before getting into the laravel passport integration. You need to get familiar with a few terms regarding authentication,
OAuth
Oauth is an authorisation framework that doesn’t share password data, instead uses authorization tokens to prove the identity of customers and service providers.
Passport
Laravel Passport provides a full OAuth2 server implementation for your Laravel application.
Integration
To start with, we need to install laravel passport in the application,
composer require laravel/passport
Update database configurations in the .env file of the project and run the below commands,
php artisan migrate
php artisan passport:install
Now, let us do some coding.
Initially, run the below command to create a controller to write login and registration functionality.
php artisan make:controller Authcontroller
Authcontroller.php
use Validator;
use App\Models\User;
use Hash;
Login
public function login(Request $request) {
$user = User::where('email', $request->email)->first();
if ($user) {
if (Hash::check($request->password, $user->password)) {
$token = $user->createToken('Laravel Password Grant Client')->accessToken;
$response['token'] = $token;
return response($response, 200);
} else {
$response = ["message" => "Password mismatch"];
return response($response, 422);
}
}
}
Registration
public function register(Request $request) {
$rules=array(
'name' => 'required',
'email' => 'required',
'password' => 'required'
);
$messages=array(
'name.required' => 'Please enter a name.',
'email.required' => 'Please enter a email.',
'password.required' => 'Please enter a password.'
);
$validator=Validator::make($request->all(),$rules,$messages);
if($validator->fails())
{
$messages=$validator->messages();
return response()->json(["messages"=>$messages], 500);
}$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return response()->json(["user"=>$user, "message"=>"User has been created successfully"]);
}
api.php
use App\Http\Controllers\AuthController;Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);
User.php
Replace use Laravel\Sanctum\HasApiTokens;
in User.php
to use Laravel\Passport\HasApiTokens;
Now you can run the laravel application and check the urls below,
http://localhost:3000/api/register
http://localhost:3000/api/login
That’s it !! You have integrated the OAuth authentication system with your laravel project.
Also read: