Hello Artisan,
In this tutorial, I am going to show you how to create API authentication in the Laravel 9 application using Laravel passport. Some days ago, I showed you how we can create API authentication using a custom token in Laravel 9.
But in this example, we will see step by step how to create a Laravel 9 passport API authentication tutorial, I will show you step by step so that you can understand it easily and I will create a register
, login
, and logout
API with Laravel passport.
So if you don't know how to create passport-based API authentication, then this example is going to be a perfect example for you. You know that Laravel 9 Passport provides a way to create auth tokens for validating users.
This tutorial will help you to create your Laravel 9 rest API with passport. We will learn Laravel 9 passport API auth tutorial. This article goes into detail on Laravel 9 rest API authentication. It's a simple example of the Laravel 9 passport oauth2 example step by step.
You have to just follow a few steps to get the following web services.
Above three APIs through you can simply get by following few steps. It is from scratch so just follow the below step, at last, I attach a screenshot of the API test from the postman.
Now, let's start laravel 9 passport tutorial.
Step 1 : Install Laravel
In the first step, we require to get a fresh Laravel 9 application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel ApiAuth
Step 2: Install Passport Package
In this step, we have to laravel/passpor
package for passport method so one your terminal and fire bellow command:
composer require laravel/passport
After successfully installing the package, open the config/app.php
file and add a service provider.
config/app.php
'providers' => [
....
Laravel\Passport\PassportServiceProvider::class,
],
Step 3: Run Migration Command
Read also : Laravel 8.x API Permissions Using Passport Scope
After the Passport service provider registers, we require to run migration command, after run migration command you will get several new tables in the database. So, let's run bellow command:
php artisan migrate
Next, we need to install the laravel passport using the command, Using passport:install
command, it will create token keys for security. So let's run bellow command:
php artisan passport:install
Step 4: Passport Configuration
In this step, we have to configuration on three place model, service provider, and auth config file. So you have to just follow changes on that file.
app/User.php
namespace App\Models;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function authAcessToken(){
return $this->hasMany('\AppModels\OauthAccessToken');
}
public function saveUser($request) : self
{
$this->name = $request->name;
$this->email = $request->email;
$this->password = bcrypt($request->password);
$this->save();
return $this;
}
public function logout() : self
{
auth()->user()->token()->revoke();
return $this;
}
}
Now update auth service provider like below:
app/Providers/AuthServiceProvider.php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
if (! $this->app->routesAreCached()) {
Passport::routes();
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
}
}
}
Now configure our auth.php file. Here are the default API driver is token. Just replace it with a passport.
config/auth.php
return [
.....
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
.....
]
Step 5 : Setup API Route
In this step, we will create API routes. Laravel provides an api.php file for writing web services routes. So, let's add a new route to that file.
routes/api.php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;
Route::post('register',[AuthController::class,'register']);
Route::post('login',[AuthController::class,'login']);
Route::group(['middleware' => ['auth:api']], function () {
Route::post('logout', [AuthController::class, 'logout']);
});
Step 6 : Create Controller
In the last step we have to create a new controller and three API methods, So first create a new directory "API" on the Controllers folder. So let's create UserController and put bellow code:
app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Helper\HasApiResponse;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\RegisterRequest;
class AuthController extends Controller
{
use HasApiResponse;
public function register(RegisterRequest $request, User $user)
{
$user = $user->saveUser($request);
return $this->httpCreated($user, 'User created successfully!');
}
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if(Auth::attempt($credentials)){
$user['user'] = Auth::user();
$user['token'] = Auth::user()->createToken('myApp')->accessToken;
return $this->httpSuccess($user, 'User login successfully.');
}
return $this->httpUnauthorizedError('Unauthorised.', ['error'=>'Username or email is not matched in our records!']);
}
public function logout(User $user)
{
$user->logout();
return response()->json(['Success' => 'Logged out'], 200);
}
}
Read also: Laravel 9 REST API Authentication Example using Sanctum
Step 7: Create Helper Trait
In this step, we have to create a helper trait to manage and handle our API response. So create it in the following path:
app\Helper\HasApiResponse.php
namespace App\Helper;
use Symfony\Component\HttpFoundation\Response;
Trait HasApiResponse
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function httpCreated($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, Response::HTTP_CREATED);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function httpNotFoundError($error, $errorMessages = [])
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, Response::HTTP_NOT_FOUND);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function httpUnauthorizedError($error, $errorMessages = [])
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, Response::HTTP_UNAUTHORIZED);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function httpSuccess($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, Response::HTTP_OK);
}
}
Step 8: Create Form Request
In this step, we will create a register form request to validate our register data. To create it run the below command:
php artisan make:request RegisterRequest
Now update this file like:
app\Http\Requests\RegisterRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:50',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
];
}
public function messages()
{
return [
'name.required' => 'Name is required field!',
'name.required' => 'Email is required field!',
'password.required' => 'Password is required!',
'c_password.required' => 'Password and confirm password must be same!'
];
}
}
Read also: Laravel 9 Custom Token Based Api Authentication Tutorial
Now we are ready to run our laravel 9 passport tutorial example project. so run bellow command.
php artisan serve
Now, we can simply test by rest-client tools, So I test it and you can see below screenshot.
Before Register Api
After Completing Register API
Before Login API
After Login API
Now, we will test the logout API, In this API you have to set three headers as listed below:
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer'
]
So, make sure above header, otherwise, you can not be able to logout.
So we successfully completed our laravel 9 passport rest api authentication tutorial. I hope it can help you.
#laravel #laravel-9x #api #laravel-passport #a #api-auth