Posted on July 31, 2021
Original post is here.

You already know that OAuth 2.0 protocol is used for authentication and authorization. Laravel has Passport, which is a full Oauth 2.0 server implementation, used for authentication over API. By default, Laravel Passport has 4 types of Grants.
But unfortunately, for project purposes, we may need custom grants. I had to make a custom grant in my last project. In that project, users can log in through OTP. I did not find any solutions on Google. So, I jumped to solve the problem on my own. Through this post, I am going to show you how can you make a custom grant in your project in a very simple way.
In your laravel project root directory, open terminal and run
composer require laravel/passportPassport needs database tables to save client tokens and related information.
php artisan migrateTo generate secure access tokens run,
php artisan passport:installAdd the Laravel\Passport\HasApiTokens trait to your App\User model. And use it.
use HasApiTokens, Notifiable;Update the config/auth.php as below,
'api' => [
'driver' => 'passport',
'provider' => 'users',
],In AuthServiceProvider, I add a method to create OTPGrant.
protected function makeOtpGrant()
{
$grant = new OtpGrant(
$this->app->make(RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}My boot function is like below,
public function boot()
{
$this->registerPolicies();
app(AuthorizationServer::class)->enableGrantType(
$this->makeOtpGrant(), Passport::tokensExpireIn()
);
Passport::routes();
}AuthServiceProvider.php
https://gist.github.com/mrron313/b342732ff3a48e7b9f892e85487e3c98#file-authserviceprovider-php
Now make a class for OTPGrant, in app/Auth/Grants folder. Our OTPGrant class is like below.
https://gist.github.com/mrron313/521752911fdf7ef89affa7524744d22d#file-otpgrant-php
In my case, there are multiple OTP verifiers which will verify the OTP. In the API request body, there will be a parameter called otp_verifier. OtpVerifierFactory class is responsible for creating OTPVerifier based on the otp_verifier parameter. otp_verifier is an optional field. If it is not provided in the request body, OtpVerifierFactory will create a verifier object of BL_INTERNAL. OtpException throws exception for invalid OTP.

In response, the client will get Access Token.

We are done. Enjoy your hot new custom grant.