laravel-impersonate icon indicating copy to clipboard operation
laravel-impersonate copied to clipboard

Impersonating only works if both users have the same password

Open Arne1303 opened this issue 2 years ago • 36 comments

Using laravel/framework: 9.17

We've been using the package for quite a while without problems but it looks like it broke in a recent dependency update.

When initiating an impersonation (using the route defined in Route::impersonate()) the user gets logged out and redirected to login, the impersonation does however work if both users (the impersonating and the one being impersonated) have the same password.

Does someone else also experience this behavior/is there a known workaround? Thanks!

Arne1303 avatar Jul 04 '22 16:07 Arne1303

Hello,

Same problem but since I used the "auth.session" middleware. If you use only "auth" middleware then no problem appears.

XternalSoft avatar Jul 04 '22 21:07 XternalSoft

Same problem here, and I'm using sanctum ... any workaround ?

adantart avatar Jul 21 '22 23:07 adantart

@adantart I got it working by removing the password from the session when leaving the impersonation, haven't got any problems but still use with caution:

Add a new Session guard:

<?php

namespace App\Auth;

class SessionGuard extends \Lab404\Impersonate\Guard\SessionGuard
{
    /**
     * @inheritDoc
     */
    public function quietLogout()
    {
        parent::quietLogout();

        foreach (array_keys(config('auth.guards')) as $guard) {
            $this->session->remove('password_hash_' . $guard);
        }
    }
}

Use the new Session guard in AuthServiceProvider (should already exist):

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        /** @var AuthManager $auth */
        $auth = $this->app['auth'];

        $auth->extend(
            'session',
            function (Application $app, $name, array $config) use ($auth) {
                $provider = $auth->createUserProvider($config['provider']);
                return new \App\Auth\SessionGuard($name, $provider, $app['session.store']);
            });
    }
}

Arne1303 avatar Jul 23 '22 14:07 Arne1303

@Arne1303 Interested to make a PR?

MarceauKa avatar Jul 23 '22 19:07 MarceauKa

@MarceauKa Sure! Should be there by Monday

Arne1303 avatar Jul 23 '22 19:07 Arne1303

Hi @MarceauKa When do you think this PR will be merged? :)

eriktobben avatar Jul 26 '22 13:07 eriktobben

@Arne1303 ...

I got this error App\Providers\AuthServiceProvider::App\Providers{closure}(): Argument #1 ($app) must be of type App\Providers\Application, Illuminate\Foundation\Application given, called in

pointing to your line: function (Application $app, $name, array $config) use ($auth) {

adantart avatar Aug 20 '22 22:08 adantart

@adantart Looks like you importer the wrong Application class, you need to change the imposer or if it is used somewhere else specify it just for that function.

You can also remove the type hint completely, that one works 2.

Arne1303 avatar Aug 20 '22 22:08 Arne1303

I don't understand ... I created the first piece of code in app folder Auth/SessionGuard.php and then I add the second piece in the boot() function of my AuthServiceProvider, now it's like this:

<?php

namespace App\Providers;

use App\Models\Team;
use App\Policies\TeamPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Team::class => TeamPolicy::class,
    ];

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

        //


        /** @var AuthManager $auth */
        $auth = $this->app['auth'];

        $auth->extend(
            'session',
            function (Application $app, $name, array $config) use ($auth) {
                $provider = $auth->createUserProvider($config['provider']);
                return new \App\Auth\SessionGuard($name, $provider, $app['session.store']);
            });
    }
}

adantart avatar Aug 20 '22 22:08 adantart

Ok, I noticed the Application namespace ... and I added

\Illuminate\Foundation\Application $app, ...

adantart avatar Aug 20 '22 22:08 adantart

Ok, I tested it , but it stills logs out when I "leave impersonation"

adantart avatar Aug 20 '22 22:08 adantart

Ok, working !!!

But I had to use my leave-impersionation method (I mean, not using the route('impersonate.leave') provided by the library, and put it in a "non admin middleware" scope, if not the "impersonate user" had no access to the method.

But yes, now it's working ...

in a certain way ... :-P

adantart avatar Aug 20 '22 22:08 adantart

@adantart can you share your code please? I can't get it working :(

@Arne1303 can you please assist?

I have create the directory App\Auth with file SessionGuard.php

`<?php

namespace App\Auth;

class SessionGuard extends \Lab404\Impersonate\Guard\SessionGuard { /** * @inheritDoc */ public function quietLogout() { parent::quietLogout();

    foreach (array_keys(config('auth.guards')) as $guard) {
        $this->session->remove('password_hash_' . $guard);
    }
}

}`

My AuthServiceProvider looks like :

`public function boot() { $this->registerPolicies();

    //


    /** @var AuthManager $auth */
    $auth = $this->app['auth'];

    $auth->extend(
        'session',
        function (\Illuminate\Foundation\Application $app, $name, array $config) use ($auth) {
            $provider = $auth->createUserProvider($config['provider']);
            return new \App\Auth\SessionGuard($name, $provider, $app['session.store']);
        });
}`

Route

Route::middleware(['auth:sanctum','verified','authadmin'])->group(function(){ Route::get('/impersonate/user/{user_id}', 'App\Http\Controllers\ImpersonateController@index')->name('impersonate');

writehow avatar Sep 26 '22 22:09 writehow

@writehow Can you check if youre custom SessionGuard is being used? My first guess would be cache, try php artisan optimize:clear

If it still doenst work I created a PR (https://github.com/404labfr/laravel-impersonate/pull/163) which does replace the password hashes with the ones from the new user instead of scrubing them of, you could try to adapt that one

Arne1303 avatar Sep 27 '22 07:09 Arne1303

@Arne1303 Thank you for the quick reply ! I will try it immediately and will let you know.

writehow avatar Sep 27 '22 08:09 writehow

@Arne1303 (and @writehow) Your code works ... but it has a side effect: no events of Auth (or sessionguard) are fired.

If I use your code, the bug we are talking here is fixed, ok but no events fired.

If I comment the code, Auth events works perfectly

adantart avatar Sep 29 '22 15:09 adantart

I have the same issue with the side effect. I also found another side effect. Stopping impersonation now logs the user out completely instead of returning to the original user.

mrpritchett avatar Oct 14 '22 23:10 mrpritchett

@adantart @mrpritchett I've used slightly different code in my pr #163 can you check if the side effects are also present there?

Arne1303 avatar Oct 15 '22 10:10 Arne1303

You mean this patch, right ? https://github.com/404labfr/laravel-impersonate/pull/163/commits/a306583cd8e2294082d0a272316dda99ca8d1169

adantart avatar Oct 15 '22 16:10 adantart

Yes, there are 2 versions, one is further up in this comment thread and one is the patch submitted, which one did you use?

Arne1303 avatar Oct 15 '22 16:10 Arne1303

I'm still getting logged out with that PR when I try to leave impersonation.

mrpritchett avatar Oct 15 '22 17:10 mrpritchett

Sorry for taking so long to answer :-P

So ... @Arne1303 ... the last one works.

SUMMARY:

In your first solution (https://github.com/404labfr/laravel-impersonate/issues/162#issuecomment-1193132174) your modifications involved

  • to extend the session through the boot function of AuthServiceProvider
  • to remove the password_hash_ in the quietLogout

As I said, this patched the problem, but affected to the events of Auth, since they were not triggered properly.

In your second solution (https://github.com/404labfr/laravel-impersonate/commit/a306583cd8e2294082d0a272316dda99ca8d1169) your modifications involved:

  • to update the password hash in the quietLogin

This second solution is cleaner than the first one ;-) and also allow Auth events to be triggered.

For example I had this in my EventServiceProvider:

class EventServiceProvider extends ServiceProvider
{
    //...

    protected $listen = [
        Login::class => [ \App\Listeners\Login::class ],
        Logout::class => [ \App\Listeners\Logout::class ],
        PasswordReset::class => [ \App\Listeners\PasswordReset::class ],
 
   //...
}

since I do some stuff when Login, Logout, ... are performed.

Now they are working well, and impersonation works perfectly although users have same or different password.

THANK YOU !

adantart avatar Oct 19 '22 17:10 adantart

@Arne1303 - I'm still seeing a log out when leaving impersonation.

mrpritchett avatar Oct 25 '22 00:10 mrpritchett

The error has "arrived" again after some update in the last week :-( I don't know if the problem is 1.7.4 ... but again, only impersonates correctly when users have the same password :-(

adantart avatar Feb 22 '23 23:02 adantart

@adantart I can confirm this issue is still unresolved for me as well.

mrpritchett avatar Feb 23 '23 00:02 mrpritchett

@adantart I can confirm this issue is still unresolved for me as well.

Weird thing here is that it was "fixed" for me, until a week ago or so ... maybe an update :-(

adantart avatar Feb 23 '23 08:02 adantart

I am getting this issue as well, impersonating a user logs the user out, Laravel 10.10.1 Jetstream/Fortify

BigBlockStudios avatar May 19 '23 19:05 BigBlockStudios

public function boot()
    {
        // Build out the impersonation event listeners - Otherwise we get a redirect to login if not setting the password_hash_sanctum when using sanctum.
        Event::listen(function (TakeImpersonation $event) {
            session()->put([
                'password_hash_sanctum' => $event->impersonated->getAuthPassword(),
            ]);
        });

        Event::listen(function (LeaveImpersonation $event) {
            session()->remove('password_hash_web');
            session()->put([
                'password_hash_sanctum' => $event->impersonator->getAuthPassword(),
            ]);
            Auth::setUser($event->impersonator);
        });
    }
    ```
    
    Try the above in the EventServiceProvider

tonypartridge avatar May 22 '23 07:05 tonypartridge

public function boot()
    {
        // Build out the impersonation event listeners - Otherwise we get a redirect to login if not setting the password_hash_sanctum when using sanctum.
        Event::listen(function (TakeImpersonation $event) {
            session()->put([
                'password_hash_sanctum' => $event->impersonated->getAuthPassword(),
            ]);
        });

        Event::listen(function (LeaveImpersonation $event) {
            session()->remove('password_hash_web');
            session()->put([
                'password_hash_sanctum' => $event->impersonator->getAuthPassword(),
            ]);
            Auth::setUser($event->impersonator);
        });
    }
    ```
    
    Try the above in the EventServiceProvider

Thanks - yes that works just fine! :)

BigBlockStudios avatar May 22 '23 12:05 BigBlockStudios

Great!

tonypartridge avatar May 22 '23 12:05 tonypartridge