Integration Passport with Laravel
1 min readMay 7, 2021
- First of all download passport dependency using the below command composer require laravel/passport
- Then add the HasApiTokens trait in your User model.
- Now, add Passport::routes(); in AuthServiceProvider -> boot().
- Then run php artisan migrate. This command generates the necessary tables for the passport.
- Now, run php artisan passport:install. This command generates keys for our passport client
- So, now our passport installation and configuration have been done. Now, we need to authenticate our APIs using passport generated token.
- For that, we’ve to create one controller suppose AuthController and use the below code sample where your login function available
$login_data = $request->all();
if (Auth::attempt(['email' => $login_data['email'], 'password' => $login_data['password']])) {
$user = Auth::user();
$token = $user->createToken('passport-demo')->accessToken;
//^^^^^$token have our access token using that we can authenticate our APIs
}
- One last thing we’ve to do that which routes need authentication those routes should add in auth:api middleware. For Example:
Route::post('login', [AuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::get('profile', [AuthController::class, 'profile']);
});
- In the above code snippet login route should be accessible without a login so, I put that route outside the middleware group and the profile route must access only to authenticate the user. So, that route I put inside middleware group.