Create Custom Grant in Laravel Passport

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.

Installation

composer require laravel/passport

Passport needs database tables to save client tokens and related information.

php artisan migrate

To generate secure access tokens run,

php artisan passport:install

Add 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',
],

Custom 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

Now make a class for OTPGrant, in app/Auth/Grants folder. Our OTPGrant class is like below.

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.

API Request/Response Example

In response, the client will get Access Token.

We are done. Enjoy your hot new custom grant.

Don’t forget to press 👏 as much as you can so that others can reach it. Make sure to follow my Medium and LinkedIn profile, to get the latest updates of mine.

Software Engineer | Professional Scrum Master | Research Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store