PHPackages                             incorp/laravel-jwt-impersonate - 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. incorp/laravel-jwt-impersonate

Abandoned → [rickycezar/laravel-jwt-impersonate](/?search=rickycezar%2Flaravel-jwt-impersonate)Library[Authentication &amp; Authorization](/categories/authentication)

incorp/laravel-jwt-impersonate
==============================

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

1.3.0(6y ago)11.0kMITPHPPHP ^7.1.3

Since Feb 16Pushed 6y ago1 watchersCompare

[ Source](https://github.com/IncorpTech/laravel-jwt-impersonate)[ Packagist](https://packagist.org/packages/incorp/laravel-jwt-impersonate)[ RSS](/packages/incorp-laravel-jwt-impersonate/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (5)Versions (18)Used By (0)

Incorp Laravel JWT Impersonate
==============================

[](#incorp-laravel-jwt-impersonate)

**DISCLAIMER:** This is a project meant to fit the needs of a private company. This means this repository will not focus on flexibe open-source driven development, rather it will be changed and altered as the company sees fit.

**Laravel JWT Impersonate** makes it easy to **authenticate as your users**. Add a simple **trait** to your **user model** and impersonate as one of your users in one click.

- [Requirements](#requirements)
- [Installation](#installation)
- [Simple usage](#simple-usage)
    - [Using the built-in controller](#using-the-built-in-controller)
- [Advanced Usage](#advanced-usage)
    - [Defining impersonation authorization](#defining-impersonation-authorization)
    - [Using your own strategy](#using-your-own-strategy)
    - [Middleware](#middleware)
    - [Exceptions](#exceptions)
    - [Events](#events)
- [Configuration](#configuration)

Requirements
------------

[](#requirements)

- Laravel &gt;= 5.8
- PHP &gt;= 7.1
- JWT-Auth &gt;= dev-develop

Installation
------------

[](#installation)

- Require it with Composer:

```
composer require incorp/laravel-jwt-impersonate
```

- Add the service provider at the end of your `config/app.php`:

```
'providers' => [
    // ...
    Incorp\Impersonate\ImpersonateServiceProvider::class,
],
```

- Add the trait `Incorp\Impersonate\Models\Impersonate` to your **User** model.

Simple usage
------------

[](#simple-usage)

Impersonate a user:

```
$token = Auth::user()->impersonate($other_user);
// You're now logged as the $other_user and the authentication token is stored in $token.
```

Leave impersonation:

```
$token = Auth::user()->leaveImpersonation();
// You're now logged as your original user and the authentication token is stored in $token.
```

### Using the built-in controller

[](#using-the-built-in-controller)

In your routes file you can call the `impersonate` route macro if you want to use the built-in controller.

```
Route::impersonate();
```

Alternatively, you can execute this macro with your `RouteServiceProvider`.

```
namespace App\Providers;

class RouteServiceProvider extends ServiceProvider
{
    public function map() {
        Route::middleware('web')->group(function (Router $router) {
            $router->impersonate();
        });
    }
}
```

```
// Where $id is the ID of the user you want impersonate
route('impersonate', $id) //the url path is "impersonate/take/{id}".
```

```
// Generate an URL to leave current impersonation
route('impersonate.leave') //the url path is "impersonate/leave".
```

```
// Check the current user impersonation status
route('impersonate.info') //the url path is "impersonate/info".
```

Advanced Usage
--------------

[](#advanced-usage)

### Defining impersonation authorization

[](#defining-impersonation-authorization)

By default all users can **impersonate** an user.
You need to add the method `canImpersonate()` to your user model:

```
    /**
     * @return bool
     */
    public function canImpersonate()
    {
        // For example
        return $this->is_admin == 1;
    }
```

By default all users can **be impersonated**.
You need to add the method `canBeImpersonated()` to your user model to extend this behavior:

```
    /**
     * @return bool
     */
    public function canBeImpersonated()
    {
        // For example
        return $this->can_be_impersonated == 1;
    }
```

### Using your own strategy

[](#using-your-own-strategy)

It is possible to implement your own controller to deal with impersonation:

```
use Incorp\Impersonate\Services\ImpersonateManager;

class ImpersonateController extends Controller
{
    protected $manager;

    // Dependency Injection
    public function __construct(ImpersonateManager $manager)
    {
        $this->manager = $manager;
    }

    public function impersonate(){ /*....*/ }
    public function leave(){ /*....*/ }
}
```

```
class ImpersonateController extends Controller
{
    protected $manager;

    //Direct app call
    public function __construct()
    {
        $this->manager = app('impersonate');
    }

    public function impersonate(){ /*....*/ }
    public function leave(){ /*....*/ }
}
```

- Working with the manager:

```
$manager = app('impersonate');

// Find a user by its ID
$manager->findUserById($id);

// TRUE if you are impersonating an user.
$manager->isImpersonating();

// Impersonate a user. Pass the original user and the user you want to impersonate. Returns authentication token
$token = $manager->take($from, $to);

// Leave current impersonation. Returns authentication token
$token = $manager->leave();

// Get the impersonator ID
$manager->getImpersonatorId();
```

### Middleware

[](#middleware)

**Protect From Impersonation**

You can use the middleware `impersonate.protect` to protect your routes against user impersonation.
This middleware can be useful when you want to protect specific pages like users subscriptions, users credit cards, ...

```
Router::get('/my-credit-card', function() {
    echo "Can't be accessed by an impersonator";
})->middleware('impersonate.protect');
```

### Exceptions

[](#exceptions)

There are six possible exceptions thrown by the service:

- `AlreadyImpersonatingException` is thrown when an impersonator tries to take another persona without leaving the first one.
- `CantBeImpersonatedException` is thrown when the method `canBeImpersonated()` fails.
- `CantImpersonateException` is thrown when the method `canImpersonate()` fails.
- `CantImpersonateSelfException` is thrown when an user tries to impersonate self.
- `NotImpersonatingException` is thrown when an user tries to leave an impersonation without being impersonating.
- `ProtectedFromImpersonationException` is thrown when an impersonator tries to get access to a route protected by the middleware.

Each exception have a message and a status code available through the respective methods `getErrorMessage()` and `getErrorCode()`.

### Events

[](#events)

There are two events available that can be used to improve your workflow:

- `TakeImpersonation` is fired when an impersonation is taken.
- `LeaveImpersonation` is fired when an impersonation is left.

Each events returns two properties `$event->impersonator` and `$event->impersonated` containing a User model isntance.

Configuration
-------------

[](#configuration)

The package comes with a configuration file.

Publish it with the following command:

```
php artisan vendor:publish --tag=impersonate
```

Available options:

```
    // The custom claim key used to store the original user id in the JWT token.
    'session_key' => 'impersonated_by',
```

```
    // The alias for the authentication middleware to be used in the routes.
    'auth_alias' => 'auth',
```

Licence
-------

[](#licence)

MIT

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~54 days

Recently: every ~185 days

Total

17

Last Release

2501d ago

PHP version history (2 changes)1.2.6PHP &gt;=7.0

1.3.0PHP ^7.1.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/a086b6e61bf3f666fe4516136609387ea4263ccf9ff9881fee58354699068296?d=identicon)[Rickycezar](/maintainers/Rickycezar)

---

Top Contributors

[![MarceauKa](https://avatars.githubusercontent.com/u/1665333?v=4)](https://github.com/MarceauKa "MarceauKa (35 commits)")[![Rickycezar](https://avatars.githubusercontent.com/u/7500485?v=4)](https://github.com/Rickycezar "Rickycezar (20 commits)")[![tghpow](https://avatars.githubusercontent.com/u/6094280?v=4)](https://github.com/tghpow "tghpow (14 commits)")[![mattdfloyd](https://avatars.githubusercontent.com/u/185187?v=4)](https://github.com/mattdfloyd "mattdfloyd (5 commits)")[![Konafets](https://avatars.githubusercontent.com/u/363363?v=4)](https://github.com/Konafets "Konafets (5 commits)")[![svenluijten](https://avatars.githubusercontent.com/u/11269635?v=4)](https://github.com/svenluijten "svenluijten (1 commits)")[![Lloople](https://avatars.githubusercontent.com/u/5665466?v=4)](https://github.com/Lloople "Lloople (1 commits)")

---

Tags

pluginlaravelpackageauthuserimpersonationimpersonatelaravel-packagelaravel-plugin

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/incorp-laravel-jwt-impersonate/health.svg)

```
[![Health](https://phpackages.com/badges/incorp-laravel-jwt-impersonate/health.svg)](https://phpackages.com/packages/incorp-laravel-jwt-impersonate)
```

###  Alternatives

[lab404/laravel-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

2.3k16.4M48](/packages/lab404-laravel-impersonate)[rickycezar/laravel-jwt-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

24117.6k](/packages/rickycezar-laravel-jwt-impersonate)[hapidjus/laravel-impersonate-ui

UI for 404labfr/laravel-impersonate

371.5k](/packages/hapidjus-laravel-impersonate-ui)[lab404/laravel-auth-checker

Laravel Auth Checker allows you to log users authentication, devices authenticated from and lock intrusions.

223164.9k2](/packages/lab404-laravel-auth-checker)

PHPackages © 2026

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