Laravel: Setup Laravel Passport
Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.
{
'Accept': 'application/json'
}
Generate the middleware using artisan
php artisan make:middleware ForceJsonRequestMiddleware
Content of ForceJsonRequestMiddleware.php
in handle()
function. The file locate at App/Http/Middleware/ForceJsonRequestMiddleware.php
.
$request->headers->set('Accept', 'application/json');
return $next($request);
Register the middleware to $routeMiddleware
array at app/Http/Kernel.php
.
'json.response' => \App\Http\Middleware\ForceJsonRequestMiddleware::class,
Then, we’ll also add it to the $middleware
array in the same file:
\App\Http\Middleware\ForceJsonRequestMiddleware::class,
That would make sure that the ForceJsonRequestMiddleware middleware is run on every request.
php artisan make:middleware CorsMiddleware
Update the handle()
function:
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
Register the middleware to $routeMiddleware
array at app/Http/Kernel.php
.
'cors' => \App\Http\Middleware\CorsMiddleware::class,
Then, we’ll also add it to the $middleware
array in the same file:
\App\Http\Middleware\CorsMiddleware::class,
We can use the middlewares in our api.php
routing like:
Route::group(['middleware' => ['cors', 'json.response']], function () {
// route path...
});
composer require laravel/passport
Migrating the tables
php artisan migrate
Generate secure access token using artisan
php artisan passport:install
Updating User
model
<?php
namespace App\Models;
...
use Laravel\Passport\HasApiTokens; //add the namespace
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable; //use it here
}
Registering passport routes to AuthServiceProvider
, place at boot()
function
if (!$this->app->routesAreCached()) {
Passport::routes();
}
Add passport TokenGuard
at config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport', //update this line
'provider' => 'users',
],
],
php artisan make:controller Api/AuthController
At top of the controller don’t forget to import used depedencies
use Illuminate\Support\Facades\Validator;
public function login(Request $request) {
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'msg' => $validator->errors()->all(),
'data' => []
], 422);
}
$data = $request->only('email', 'password');
if (!auth()->attempt($data)) {
return response()->json([
'success' => false,
'msg' => 'Invalid email or password',
'data' => []
]);
}
$token = auth()->user()->createToken('API Token')->accessToken;
return response()->json([
'success' => true,
'msg' => 'Logged in user data',
'data' => [
'profile' => auth()->user(),
'token' => $token
]
]);
}
public function logout(Request $request)
{
$token = $request->user()->token();
$token->revoke();
return response()->json([
'success' => true,
'msg' => 'You have been successfully logged out',
'data' => []
]);
}
Route::group(['middleware' => ['cors', 'json.response']], function () {
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::post('/logout', [AuthController::class, 'logout']);
});
});
Done!!!!