Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

How an admin can temporarily connect with another account ?

Hello,

I'm looking for a way the admin can temporarily connect as another user without loosing his own connection. In this case a button could appear at the top of the screen to come back to the admin connection.

It's probably no so hard to do, but at the moment I have no idea how to do that.

How is it possible to code this functionality ?

Thanks for your help ;).

V

0 likes
14 replies
LaryAI's avatar
Level 58

To implement a feature where an admin can temporarily connect as another user without losing their own session, you can follow these steps. This solution assumes you're using a framework like Laravel, but the general approach can be adapted to other frameworks as well.

Step 1: Create a "Switch User" Functionality

  1. Add a Route and Controller Method:

    Create a route that allows the admin to switch to another user's account. This route should be protected so that only admins can access it.

    // routes/web.php
    Route::post('/admin/switch-user/{userId}', [AdminController::class, 'switchUser'])->middleware('auth', 'admin');
    
  2. Implement the Controller Method:

    In your AdminController, implement the switchUser method. This method will store the current admin's ID in the session and then log in as the target user.

    // app/Http/Controllers/AdminController.php
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Session;
    use App\Models\User;
    
    public function switchUser($userId)
    {
        // Store the current admin's ID in the session
        Session::put('admin_id', Auth::id());
    
        // Log in as the target user
        $user = User::findOrFail($userId);
        Auth::login($user);
    
        return redirect('/dashboard'); // Redirect to the user's dashboard or desired page
    }
    

Step 2: Create a "Return to Admin" Functionality

  1. Add a Route and Controller Method:

    Create a route that allows the admin to return to their original session.

    // routes/web.php
    Route::post('/admin/return', [AdminController::class, 'returnToAdmin'])->middleware('auth');
    
  2. Implement the Controller Method:

    In your AdminController, implement the returnToAdmin method. This method will retrieve the admin's ID from the session and log them back in.

    // app/Http/Controllers/AdminController.php
    
    public function returnToAdmin()
    {
        // Retrieve the admin's ID from the session
        $adminId = Session::pull('admin_id');
    
        if ($adminId) {
            // Log back in as the admin
            $admin = User::findOrFail($adminId);
            Auth::login($admin);
        }
    
        return redirect('/admin/dashboard'); // Redirect to the admin's dashboard or desired page
    }
    

Step 3: Add UI Elements

  1. Switch User Button:

    Add a button or link in the admin panel that allows the admin to switch to another user. This could be a form that submits to the /admin/switch-user/{userId} route.

  2. Return to Admin Button:

    Add a button or link that appears when the admin is logged in as another user. This button should submit to the /admin/return route.

Security Considerations

  • Authorization: Ensure that only authorized admins can switch users. Use middleware to enforce this.
  • Session Management: Be cautious with session management to prevent session fixation attacks.
  • Audit Logging: Consider logging these actions for auditing purposes.

This approach allows an admin to switch to another user's account temporarily and return to their own session without losing their original connection.

1 like
vincent15000's avatar

Can someone explain me what the AI is saying ?

Session management: Be cautious with session management to prevent session fixation attacks.

martinbean's avatar

@vincent15000 Look into user impersonation. There will be numerous packages out there that add this functionality to Laravel.

1 like
jlrdw's avatar

@vincent15000 I don't get what you are doing. An admin should be able to do this anyway using authorization. Like @jeffreyway can pull up me or you and never leave admin. Sorry if I misunderstand.

1 like
vincent15000's avatar

@jlrdw When the admin is connected, In the users list, I want to add a Connect as button so that the admin can temporarily connect as a specific user to be able to has exactly the same views as this user.

I just didn't know how to do and I didn't know what impersonation was.

Snapey's avatar
Snapey
Best Answer
Level 122

I usually do it the other way around, using a middleware.

On instigating impersonation, put the user to be impersonated into session.

In middleware on every route, if the session value impersonate is set, use theAuth::loginUsingId(); method and use the impersonate value.

A route that can be called by anyone clears the session value to drop out of impersonation. The admin is not required to login afterwards.

I usually add a banner fixed to the top of the screen, in bright yellow that says which user is being impersonated and a link to end termination.

1 like
vincent15000's avatar

@Snapey

I have tried and it seems to work fine.

I have this middleware.

public function handle(Request $request, Closure $next)
{
    if (session()->has('impersonate_id')) {
        $id = session('impersonate_id');

        $user = User::find($id);

        if ($user && !$user->isAdmin()) {
            auth()->login($user);
        }
    }
            
    return $next($request);
}

These routes.

Route::middleware(['auth', 'verified', 'actif', 'impersonate'])->group(function () {

    // IMPERSONATE BACK TO ADMIN
    Route::delete('impersonate', [UserController::class, 'backToAdmin'])->name('admin.impersonate.destroy');

    // ADMIN
    Route::prefix('admin/')->name('admin.')->middleware(['admin'])->group(function () {
        Route::post('impersonate/{user}', [UserController::class, 'switchUser'])->name('impersonate.create');
    });
});

And the corresponding functions in the controller.

Can you just tell me if it looks correct ?

But doing like this, is there any risk that a user is able to switch to admin by sending a request to the admin.impersonate.destroy route for example from Postman ?

Snapey's avatar

@vincent15000 This isn't the same as I proposed. My way keeps the admin logged in as admin and then switches the session over to the specified user on every request.

1 like
vincent15000's avatar

@Snapey Ok thank you ... your solution seems to be better ... but I don't understand how to code it.

Snapey's avatar

@vincent15000

middleware

public function handle(Request $request, Closure $next)
{
    if (session()->has('impersonate_id')) {

            Auth::loginUsingId(session('impersonate_id');

    }
            
    return $next($request);
}

controller

public function switchUser(Request $request, User $user)
{
    $this->authorize('switchUser', $user);

    session()->put( 'impersonate_id', $user->id);

    return redirect()->route('dashboard');
}


public function backToAdmin(Request $request)
{

	session()->forget('impersonate_id');

    return redirect()->route('dashboard');

}

make sure your middleware is after the session has been restored, and before any middleware that uses the authenticated user.

1 like
vincent15000's avatar

@Snapey Hmmm ... I thought I did so ... is there a difference between Auth::loginUsingId() and auth()->login() ? Except that you have to use only an id or the user object ... is there any other difference ?

When I have saved the user_id (I called it user_id instead of impersonate_id) in the session and logged in the user with auth()->login($user);, when I delete the impersonate_id in the session, there was no session for the admin that was connected, so I had to reconnect him with auth()->login().

Please or to participate in this conversation.