PHPackages                             leandrodiogenes/passport-multiauth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. leandrodiogenes/passport-multiauth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

leandrodiogenes/passport-multiauth
==================================

Add support to multi-auth on Laravel Passport

v6.0.1(6y ago)018MITPHPPHP ^7.2

Since Oct 10Pushed 6y agoCompare

[ Source](https://github.com/leandrodiogenes/passport-multiauth)[ Packagist](https://packagist.org/packages/leandrodiogenes/passport-multiauth)[ RSS](/packages/leandrodiogenes-passport-multiauth/feed)WikiDiscussions 6.x Synced 2d ago

READMEChangelog (1)Dependencies (4)Versions (23)Used By (0)

Laravel Passport Multi-Auth
===========================

[](#laravel-passport-multi-auth)

[![Latest Stable Version](https://camo.githubusercontent.com/4885b5ce594efd782d7bb73d739c58a4d5b386f560091a0046c8abfacf351637/68747470733a2f2f706f7365722e707567782e6f72672f736d617274696e732f70617373706f72742d6d756c7469617574682f762f737461626c65)](https://packagist.org/packages/smartins/passport-multiauth)[![Build Status](https://camo.githubusercontent.com/0c3243c2026bf27669b2e3ef0a253b12fcbbe87624cdb5a035ceba011d5f5910/68747470733a2f2f7472617669732d63692e6f72672f7366656c69782d6d617274696e732f70617373706f72742d6d756c7469617574682e7376673f6272616e63683d362e78)](https://travis-ci.org/sfelix-martins/passport-multiauth)[![Code Coverage](https://camo.githubusercontent.com/b3f27be552aeae9ea332494c384635e8b62965deb13a370ef5b64a99f1872e6b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7366656c69782d6d617274696e732f70617373706f72742d6d756c7469617574682f6261646765732f636f7665726167652e706e673f623d362e78)](https://scrutinizer-ci.com/g/sfelix-martins/passport-multiauth/?branch=6.x)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/795cae6e73b68606050b83f0bfe970edb147f662fe850df47dd4a0716b26a963/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7366656c69782d6d617274696e732f70617373706f72742d6d756c7469617574682f6261646765732f7175616c6974792d73636f72652e706e673f623d362e78)](https://scrutinizer-ci.com/g/sfelix-martins/passport-multiauth/?branch=6.x)[![StyleCI](https://camo.githubusercontent.com/f210665ccf451486c001d2fc47a8f4435c634c42039cf405e447e3842a4d8766/68747470733a2f2f7374796c6563692e696f2f7265706f732f3130363231383538362f736869656c643f6272616e63683d362e78)](https://styleci.io/repos/106218586)[![License](https://camo.githubusercontent.com/2835945567f53abbcc8821ed571b6f8d9ee55a61fb62a179715c386bf74623a8/68747470733a2f2f706f7365722e707567782e6f72672f736d617274696e732f70617373706f72742d6d756c7469617574682f6c6963656e7365)](https://packagist.org/packages/smartins/passport-multiauth)[![Donate](https://camo.githubusercontent.com/604e3db9c8751116b3f765aad0353ec7ded655bbe8aaacbc38d8c4a6b784b3ed/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f446f6e6174652d50617950616c2d677265656e2e737667)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=AEXFGV23MM386&source=url)

Add multi-authentication support to [Laravel Passport](https://laravel.com/docs/5.5/passport)

Upgrading from 4.0 to 5.0
-------------------------

[](#upgrading-from-40-to-50)

- To upgrade from version 4.0 to 5.0 folow [this guide](https://github.com/sfelix-martins/passport-multiauth/blob/5.0/UPGRADE.md)

Upgrading from 2.0 to 3.0
-------------------------

[](#upgrading-from-20-to-30)

- To upgrade from version 2.0 to 3.0 folow [this guide](https://github.com/sfelix-martins/passport-multiauth/blob/3.0/UPGRADE.md)

Upgrading from 1.0 to 2.0
-------------------------

[](#upgrading-from-10-to-20)

- To upgrade from version 1.0 to 2.0 follow [this guide](https://github.com/sfelix-martins/passport-multiauth/blob/2.0/UPGRADE.md)

Compatibility
-------------

[](#compatibility)

Laravel Passport^5.0^6.0^7.0^8.0Laravel FrameworkPassport Multiauth&lt;= 5.6&lt;= 3.05.7.x4.0.x&gt;= 5.7.x &lt;= 5.8.x5.0.x&gt;= 6.x6.xInstalling and configuring
--------------------------

[](#installing-and-configuring)

Install using composer:

```
$ composer require smartins/passport-multiauth
```

To all works fine, we need to ensure that the `SMartins\PassportMultiauth\Providers\MultiauthServiceProvider::class` service provider be registered before `Laravel\Passport\PassportServiceProvider::class`.

Firstly, you will remove the `laravel/passport` package from Laravel [Package Discovery](https://laravel.com/docs/5.8/packages#package-discovery).

In your `composer.json` file, add the `laravel/passport` to `extra.laravel.dont-discover` array:

```
    "extra": {
        "laravel": {
            "dont-discover": [
                "laravel/passport"
            ]
        }
    },
```

And register the providers manually on `config/app.php`:

```
    'providers' => [
        // ...
        SMartins\PassportMultiauth\Providers\MultiauthServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class,
    ],
```

**WARNING:** The provider `SMartins\PassportMultiauth\Providers\MultiauthServiceProvider::class` MUST be added before `Laravel\Passport\PassportServiceProvider::class` to it works fine.

Maybe you will need clear the bootstrap cache files to re-register the providers:

```
php artisan optimize:clear
```

Migrate database to create `oauth_access_token_providers` table:

```
$ php artisan migrate
```

**NOTE** If you don't ron the command to install passport run:

```
$ php artisan passport:install
```

Instead of using the `Laravel\Passport\HasApiTokens` trait from [Laravel Passport](https://laravel.com/docs/5.6/passport#installation) core, use the trait `SMartins\PassportMultiauth\HasMultiAuthApiTokens`.

Internally, this `HasMultiAuthApiTokens` uses the `HasApiTokens`, overriding the methods `tokens()` and `createToken($name, $scopes = [])`. The behavior of the method `tokens()` was changed to join with the table `oauth_access_token_providers` getting just the tokens created to specific model. The method `createToken($name, $scopes = [])` was changed to create the token using the `provider` defined to model on `config/auth.php`. Now when you create the token, this token will be related with the model that is calling.

Add new provider in `config/auth.php` using a model that extends of `Authenticatable` class and use `HasMultiAuthApiTokens` trait.

Example:

Configure your model:

```
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use SMartins\PassportMultiauth\HasMultiAuthApiTokens;

class Admin extends Authenticatable
{
    use Notifiable, HasMultiAuthApiTokens;
}
```

And your `config/auth.php` providers:

```
    // ...

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        // ** New provider**
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
    ],

    // ...
```

Add a new `guard` in `config/auth.php` guards array using driver `passport` and the provider added above:

```
    // ...

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

        // ** New guard **
        'admin' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

    // ...
```

Register the middleware `AddCustomProvider` to `$routeMiddleware` attributes on `app/Http/Kernel.php` file.

```
class Kernel extends HttpKernel
{
    // ...

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        // ...
        'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
    ];

    // ...
}
```

**OBS:** The param `provider` is required to routes wrapped by `AddCustomProvider` middleware. You must to pass a valid provider configured on `config/auth.php`.

Add new middleware `Authenticate` on `app/Http/Kernel` `$routeMiddleware` attribute.

```
class Kernel extends HttpKernel
{
    // ...

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        // ** New middleware **
        'multiauth' => \SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

    // ...
}
```

Encapsulate the passport routes for access token with the registered middleware in `AuthServiceProvider`. This middleware will add the capability to `Passport` route `oauth/token` use the value of `provider` param on request:

```
namespace App\Providers;

use Route;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    // ...

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

        Passport::routes();

        // Middleware `oauth.providers` middleware defined on $routeMiddleware above
        Route::group(['middleware' => 'oauth.providers'], function () {
            Passport::routes(function ($router) {
                return $router->forAccessTokens();
            });
        });
    }
    // ...
}
```

**Optional:** Publish migrations:

Just run the `vendor:publish` artisan command with package provider as parameter:

```
$ php artisan vendor:publish --provider="SMartins\PassportMultiauth\Providers\MultiauthServiceProvider"
```

If you are not going to use PassportMultiauth's default migrations, you should call the `SMartins\PassportMultiauth\PassportMultiauth::ignoreMigrations` method in the register method of your AppServiceProvider.

Usage
-----

[](#usage)

Add the `provider` parameter in your request at `/oauth/token`:

```
POST /oauth/token HTTP/1.1
Host: localhost
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Cache-Control: no-cache

{
    "username":"user@domain.com",
    "password":"password",
    "grant_type" : "password",
    "client_id": "client-id",
    "client_secret" : "client-secret",
    "provider" : "admins"
}
```

You can pass your guards on `multiauth` middleware as you wish. Example:

```
Route::group(['middleware' => ['api', 'multiauth:admin']], function () {
    Route::get('/admin', function ($request) {
        // Get the logged admin instance
        return $request->user(); // You can use too `$request->user('admin')` passing the guard.
    });
});
```

The `api` guard use is equals the example with `admin`.

You can pass many guards to `multiauth` middleware.

```
Route::group(['middleware' => ['api', 'multiauth:admin,api']], function () {
    Route::get('/admin', function ($request) {
        // The instance of user authenticated (Admin or User in this case) will be returned
        return $request->user();
    });
});
```

You can use too the `Auth` facade:

```
Auth::check();
Auth::user();
```

### Refreshing tokens

[](#refreshing-tokens)

Add the `provider` parameter in your request at `/oauth/token`:

```
POST /oauth/token HTTP/1.1
Host: localhost
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Cache-Control: no-cache

{
    "grant_type" : "refresh_token",
    "client_id": "client-id",
    "client_secret" : "client-secret",
    "refresh_token" : "refresh-token",
    "provider" : "admins"
}
```

### Using scopes

[](#using-scopes)

Just use the [`scope` and `scopes`](https://laravel.com/docs/5.5/passport#checking-scopes) middlewares from `Laravel\Passport`.

```
protected $routeMiddleware = [
    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
];
```

### Personal Access Tokens

[](#personal-access-tokens)

In your model that uses the trait `SMartins\PassportMultiauth\HasMultiAuthApiTokens` you can uses the methods `createToken($name, $scopes = [])` and `tokens()` to manage your personal access tokens. E.g.:

```
$user = User::find(1);
$admin = Admin::find(1);

// Create token from Model instance.
$user->createToken('My Token');
$admin->createToken('My Admin Token');

// Get the tokens created to this user.
$user->tokens()->each(function ($token) {
    echo $token->name; // My Token
});

$admin->tokens()->each(function ($token) {
    echo $token->name; // My Admin Token
});
```

### Known Issues

[](#known-issues)

To all works correctly you must use the default guard `web` on `config/auth.php`. E.g.:

```
    'defaults' => [
        'guard' => 'web',
    ],
```

Exists an opened [issues](https://github.com/sfelix-martins/passport-multiauth/issues/63) that will be analysed ASAP.

### Unit tests

[](#unit-tests)

Instead to use the `Laravel\Passport\Passport::actingAs()` method, use `SMartins\PassportMultiauth\PassportMultiauth::actingAs()`. The difference is that the `actingAs` from this package get the guard based on `Authenticatable` instance passed on first parameter and authenticate this user using your guard. On authenticated request (Using `auth` middleware from package - `SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate)` the guard is checked on `Request` to return the user or throws a `Unauthenticated` exception. E.g.:

```
use App\User;
use Tests\TestCase;
use SMartins\PassportMultiauth\PassportMultiauth;

class AuthTest extends TestCase
{
    public function fooTest()
    {
        $user = factory(User::class)->create();

        PassportMultiauth::actingAs($user);

        $this->json('GET', 'api/user');
    }

    public function withScopesTest()
    {
        $user = factory(User::class)->create();

        PassportMultiauth::actingAs($user, ['see-balance']);

        $this->json('GET', 'api/balance');
    }
}
```

### Sample Project

[](#sample-project)

You can see a complete `Passport-Multiauth` implementation using `Password Grant Tokens` and `Personal Access Token` on [passport-multiauth-demo](https://github.com/sfelix-martins/passport-multiauth-demo) project

### Contributors

[](#contributors)

Based on [renanwilian](https://github.com/renanwilliam) responses to [Passport Multi-Auth issue](https://github.com/laravel/passport/issues/161).

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 78.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~42 days

Recently: every ~31 days

Total

22

Last Release

2252d ago

Major Versions

v2.1.0 → v3.0.02018-09-02

v3.0.0 → v4.0.02018-10-02

v4.1.0 → v5.0.02019-06-16

3.0.x-dev → 5.0.x-dev2019-11-20

5.0.x-dev → v6.0.02020-02-10

PHP version history (3 changes)v0.1.0PHP &gt;=5.6.4

v4.0.0PHP &gt;=7.1

v6.0.0PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/4ba6f23cdbc58437fa243a252549c73ecf1c5e91ecc81d14b5a72e368d0cbe24?d=identicon)[leandrodiogenes](/maintainers/leandrodiogenes)

---

Top Contributors

[![sfelix-martins](https://avatars.githubusercontent.com/u/22901624?v=4)](https://github.com/sfelix-martins "sfelix-martins (57 commits)")[![pedmindset](https://avatars.githubusercontent.com/u/29241345?v=4)](https://github.com/pedmindset "pedmindset (3 commits)")[![Alymosul](https://avatars.githubusercontent.com/u/8314647?v=4)](https://github.com/Alymosul "Alymosul (3 commits)")[![leandrodiogenes](https://avatars.githubusercontent.com/u/2463299?v=4)](https://github.com/leandrodiogenes "leandrodiogenes (2 commits)")[![simioluwatomi](https://avatars.githubusercontent.com/u/22191563?v=4)](https://github.com/simioluwatomi "simioluwatomi (2 commits)")[![renanwilliam](https://avatars.githubusercontent.com/u/19995615?v=4)](https://github.com/renanwilliam "renanwilliam (1 commits)")[![tskvrnda](https://avatars.githubusercontent.com/u/31281421?v=4)](https://github.com/tskvrnda "tskvrnda (1 commits)")[![michaelnguyen2021](https://avatars.githubusercontent.com/u/436950?v=4)](https://github.com/michaelnguyen2021 "michaelnguyen2021 (1 commits)")[![mul14](https://avatars.githubusercontent.com/u/113989?v=4)](https://github.com/mul14 "mul14 (1 commits)")[![NikitaSNS](https://avatars.githubusercontent.com/u/17299938?v=4)](https://github.com/NikitaSNS "NikitaSNS (1 commits)")[![odupont-aprilmoto](https://avatars.githubusercontent.com/u/28052337?v=4)](https://github.com/odupont-aprilmoto "odupont-aprilmoto (1 commits)")

---

Tags

laravelpassportmulti-auth

### Embed Badge

![Health badge](/badges/leandrodiogenes-passport-multiauth/health.svg)

```
[![Health](https://phpackages.com/badges/leandrodiogenes-passport-multiauth/health.svg)](https://phpackages.com/packages/leandrodiogenes-passport-multiauth)
```

###  Alternatives

[smartins/passport-multiauth

Add support to multi-auth on Laravel Passport

285324.2k1](/packages/smartins-passport-multiauth)[corbosman/laravel-passport-claims

Add claims to Laravel Passport JWT Tokens

88655.9k](/packages/corbosman-laravel-passport-claims)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

55342.3k2](/packages/jeremy379-laravel-openid-connect)[schedula/laravel-passport-socialite

The missing laravel passport feature for social authentication

4922.6k](/packages/schedula-laravel-passport-socialite)[danjdewhurst/laravel-passport-facebook-login

Facebook Token Request Grant for Laravel Passport

2824.4k](/packages/danjdewhurst-laravel-passport-facebook-login)[mikemclin/passport-custom-request-grant

Custom Request Grant for Laravel Passport

343.6k](/packages/mikemclin-passport-custom-request-grant)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
