alvery
alvery

Reputation: 1983

Custom grant type for PassportServiceProvider (Laravel)

Tried to implement custom grant service provider according to this manual:

https://github.com/mikemclin/passport-custom-request-grant

Inside the register method we're getting the auth server instance (with helper method) and then adding our grant using AuthServer:

public function register()
    {
        app(AuthorizationServer::class)->enableGrantType($this->makeCustomRequestGrant(), Passport::tokensExpireIn());
    }

This doesn't work for me. I tried to register my grant another way:

$this->app->singleton(AuthorizationServer::class, function () {
            return tap($this->makeAuthorizationServer(), function ($server) {
                $server->enableGrantType(
                    $this->makeCustomRequestGrant(), Passport::tokensExpireIn()
                );
            });
        });

How can I "extend" my singleton server instance with another one grant? In my case I just instantiated the new one, so previous grant types become unsupported.

The main goal is to create grant that will be using another model - customers (not users) and activation codes for grant. User will attempt for codes using client_credentials and then he can make api queries using activation code grant - with another scopes.

Upvotes: 1

Views: 861

Answers (1)

Francisco Daniel
Francisco Daniel

Reputation: 1029

I know that this answer may be late but I found a way to solve this requirement.

I simply added the grant to the server in my AuthServiceProvider and extract the grant logic to a Grant Class to stay clean.

You can check the PasswordGrant class to take as a base.

Greetings!

namespace App\Providers;

use App\Auth\Grants\FacebookGrant;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Passport;
use League\OAuth2\Server\AuthorizationServer;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        app(AuthorizationServer::class)->enableGrantType(
            $this->makeFacebookGrant(), Passport::tokensExpireIn()
        );

        Passport::routes();

        //
    }

    /**
     * Create and configure a Facebook grant instance.
     *
     * @return FacebookGrant
     */
    protected function makeFacebookGrant()
    {
        $grant = new FacebookGrant(
            $this->app->make(RefreshTokenRepository::class)
        );

        $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());

        return $grant;
    }
}

Upvotes: 1

Related Questions